简体   繁体   中英

WPF Usercontrol Property Intitialization

I am playing around with WPF Usercontrols and have the following question: why does the behaviour of property initialization/assignment change after a property is made to a DependencyProperty ?

Let me briefly illustrate:

Consider this code for a UserControl class:

public partial class myUserControl : UserControl
{
    private string _blabla;
    public myUserControl()
    {
        InitializeComponent();
        _blabla = "init";
    }

    //public static DependencyProperty BlaBlaProperty = DependencyProperty.Register(
    //    "BlaBla", typeof(string), typeof(UserControlToolTip));

    public string BlaBla
    {
        get { return _blabla; }
        set { _blabla = value; }
    }
}

And this is how the UserControl is initialized in the XAML file:

<loc:myUserControl BlaBla="ddd" x:Name="myUsrCtrlName" />

The problem I have is that the line set { _blabla = value; } is called ONLY when the DependencyProperty declaration is commented out (as per this example). However when the DependencyProperty line becomes part of the program the set { _blabla = value; } line is no longer called by the system.

Can some please explain this strange behavior to me?

Thanks a million!

The CLR wrapper (getter and setter) of a dependency property should only be used to call the GetValue and SetValue methods of the dependency property.

eg

public string BlaBla
{
    get { return (string)GetValue(BlaBlaProperty) }
    set { SetValue(BlaBlaPropert, value); }
}

and Nothing more...
The reason for this is that the WPF binding engine calls GetValue and SetValue directly (eg without calling the CLR wrapper) when binding is done from the XAML.

So the reason you don't see them called is because they really aren't and that is precisely the reason why you shouldn't add any logic to the CLR Get and Set methods.

Edit
Based on OPs comment - here is an example of creating a callback method when the DependencyProperty changes:

public static DependencyProperty BlaBlaProperty = 
       DependencyProperty.Register("BlaBla", typeof(string), Typeof(UserControlToolTip), 
       new FrameworkPropertyMetadata(null, OnBlachshmaPropertyChanged));


private static void OnBlachshmaPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
        UserControlToolTip owner = d as UserControlToolTip;

        if (owner != null)
        {
            // Place logic here
        }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM