如何在依赖属性中获取/设置什么都不做?

我已经创建了一个这样的依赖属性:

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); } } //... } 

然后将它绑定到我的wpf窗口,一切正常。

当我尝试向setter添加一些逻辑时,我注意到它没有被调用。 我修改了get;现在设置为一个点,它们看起来像这样:

  get{return null;} set{} 

它仍然有效! 怎么会? GetValue / SetValue调用的用途是什么?

WPF数据绑定基础结构直接使用DependencyProperty,Xyz属性是程序员的便利接口。

在DependencyProperty.Register调用中查看PropertyMetadata ,您可以提供在属性值更改时运行的回调,这是您可以应用业务逻辑的位置。

DependencyProperty是XyzProperty的后备存储。 如果通过DependencyProperty接口访问该属性,它将完全绕过Property的Get / Set访问器。

想一想:

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

在这种情况下,如果我手动分配_myValue = 12 ,显然不会调用MyValue属性的“Set”访问器; 我彻底绕过了它! DependencyProperties也是如此。 WPF的绑定系统直接使用DependencyProperty接口。