C# 为什么get/set-in-dependency属性没有';我什么也不做?

C# 为什么get/set-in-dependency属性没有';我什么也不做?,c#,wpf,dependency-properties,C#,Wpf,Dependency Properties,我创建了一个依赖项属性,如下所示: public partial class MyControl: UserControl { //... public static DependencyProperty XyzProperty = DependencyProperty.Register("Xyz",typeof (string),typeof (MyControl),new PropertyMetadata(default(string))); public string

我创建了一个依赖项属性,如下所示:

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

   //...
}
 get{return null;}
 set{}
然后把它绑在我的wpf窗口上,一切正常

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

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

   //...
}
 get{return null;}
 set{}

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

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


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

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

这样想:

private int _myValue = 0;

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

在本例中,如果我手动分配
\u myValue=12
,显然不会调用myValue属性的“Set”访问器;我完全绕过了它!从属财产也是如此。WPF的绑定系统直接使用DependencyProperty接口。

我明白了。但我还是需要它,对吗?我试图从源代码中删除它,显然编译器会抱怨,只有在代码中引用该属性时,才需要该属性。否则它就不需要了,如果您是声明式绑定,您将使用名称“Xyz”,但将解析为依赖项属性,而不需要成员属性。这就是为什么我必须调用GetValue/SetValue right?如果我直接调用
this.Xyz=“newValue”对。Get/Set属性包装器对您来说很方便,但最终与WPF的绑定系统无关。另请参阅,了解为什么不应在属性包装器中添加任何附加逻辑。