Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howcome the get/set in dependency property doesn't do anything?

I've created a dependency property like this:

public partial class MyControl: UserControl
{
   //...

   public static DependencyProperty XyzProperty = DependencyProperty.Register("Xyz",typeof (string),typeof (MyControl),new PropertyMetadata(default(string)));

   public string Xyz
   {
       get { return (string) GetValue(XyzProperty ); }
       set { SetValue(XyzProperty , value); }            
   }

   //...
}

Then bind it to my wpf window and everything worked fine.

When I tried to add some logic to the setter I notice it wasn't being called. I modify the get;Set up to a point now they look like this:

 get{return null;}
 set{}

And it is still works! How come? What's the use of that GetValue/SetValue calls?

like image 272
OscarRyz Avatar asked Aug 10 '12 17:08

OscarRyz


2 Answers

The WPF data binding infrastructure uses the DependencyProperty directly, the Xyz property is a convenience interface for the programmer.

Take a look at the PropertyMetadata in the call to DependencyProperty.Register, you can supply a callback that will run when the property value is changed, this is where you can apply your business logic.

like image 179
Chris Taylor Avatar answered Oct 06 '22 15:10

Chris Taylor


The DependencyProperty is the backing store for the XyzProperty. If you access the property through the DependencyProperty interface, it completely bypasses the Property's Get/Set accessor.

Think of it this way:

private int _myValue = 0;

public int MyValue
{
    get { return _myValue; }
    set { _myValue = value; }
}

In this instance, if I manually assign _myValue = 12, obviously the "Set" accessor for the MyValue property won't be called; I completely bypassed it! The same is true for DependencyProperties. WPF's binding system uses the DependencyProperty interfaces directly.

like image 38
BTownTKD Avatar answered Oct 06 '22 13:10

BTownTKD