开发者

WPF UserControl Initialized event fireing before notmal properties are set

This is the situation , you can test it for yourselves : The microsoft documentation specifies that when the initialized event is fired , all the properties are set (except bindings) If you create a new user control and in the code behind file you define a simple string property, then you put this new control on a page and set that property there , when the initialized event is fired on the user control that property will not be set. What is the workaround for this except for using the loaded event (cannot do that as I am only creating the controls in memory without displaying them.

Here is the code for the user control :

Public Class UserControl1 

Private _Test As String
Public Property test() As String
    Get
        Return _Test
    End Get
    Set(ByVal v开发者_开发技巧alue As String)
        _Test = value
    End Set
End Property

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

End Sub

Protected Overrides Sub OnInitialized(ByVal e As System.EventArgs)
    'MyBase.OnInitialized(e)
    Debug.Write(_Test)
End Sub

Private Sub UserControl_Initialized(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Initialized
    Dim parent As FrameworkElement = Me.Parent
    parent = LogicalTreeHelper.GetParent(Me)
End Sub

End Class


I'm wondering why you comment out MyBase.OnInitialized(e)?

What your trying to do is to set a property on a child element via XAML. I believe the MSDN article is saying that properties for the current UserControl (if set in XAML) will be set during the call to InitializeComponent.

InitializeComponent is called during the constructor of the UserControl. The parent element (your page) will have to create the UserControl, and therefore cause the constructor to run, before setting any properties on it.

If you want your child to be notified when a property is set, simply add code to that properties setter.

Another option may be to call a sub on the child after the parent has fully loaded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜