WPF依赖属性不起作用

我有一个自定义的依赖属性定义如下:

public static readonly DependencyProperty MyDependencyProperty = DependencyProperty.Register( "MyCustomProperty", typeof(string), typeof(MyClass)); private string _myProperty; public string MyCustomProperty { get { return (string)GetValue(MyDependencyProperty); } set { SetValue(MyDependencyProperty, value); } } 

现在我尝试在XAML中设置该属性

  

但是DependencyObject中的setter永远不会被击中! 虽然我将属性更改为常规属性而不是Dep Prop时会这样做

试试这个..

  public string MyCustomProperty { get { return (string)GetValue(MyCustomPropertyProperty); } set { SetValue(MyCustomPropertyProperty, value); } } // Using a DependencyProperty as the backing store for MyCustomProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyCustomPropertyProperty = DependencyProperty.Register("MyCustomProperty", typeof(string), typeof(TargetCatalogControl), new UIPropertyMetadata(MyPropertyChangedHandler)); public static void MyPropertyChangedHandler(DependencyObject sender, DependencyPropertyChangedEventArgs e) { // Get instance of current control from sender // and property value from e.NewValue // Set public property on TaregtCatalogControl, eg ((TargetCatalogControl)sender).LabelText = e.NewValue.ToString(); } // Example public property of control public string LabelText { get { return label1.Content.ToString(); } set { label1.Content = value; } } 

它没有,除非你手动调用它。 有一个属性更改的处理程序,您可以添加到DependancyProperty构造函数调用,以便在属性更改时得到通知。

调用此构造函数:

http://msdn.microsoft.com/en-us/library/ms597502.aspx

使用此构造函数创建的PropertyMetadata实例:

http://msdn.microsoft.com/en-us/library/ms557327.aspx

编辑:此外,您没有正确实现依赖属性。 你的getset应分别使用GetValueSetValue ,你不应该有一个类成员来存储值。 DP的成员名称也应该是{PropertyName}Property ,例如,如果已注册的get / set和属性名称是MyCustomProperty ,则为MyCustomProperty 。 有关更多信息,请参见http://msdn.microsoft.com/en-us/library/ms753358.aspx 。

希望有所帮助。

也许您正在使用MVVM,并覆盖View的DataContext?

如果这样做,那么更改MyCustomProperty的事件将在原始 DataContext上引发,而不是在新的ViewModel上引发。