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

六眼飞鱼酱① 提交于 2020-01-12 18:48:05

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11906423/howcome-the-get-set-in-dependency-property-doesnt-do-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!