如何监听WPF依赖属性

因为 WPF 的所有控件都继承自 DependencyObject 的,该基类提供了对依赖属性的一些操作方法。

在 WPF 中依赖属性是这么定义的,

public int MyProperty
{
    get { return (int)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}

// Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0));

所以我们在设置依赖依赖属性的值时可以调用 SetValue 方法,这就导致了 你在 MyProperty 属性的 set 里下断点,然而属性变更了但是断点却没有进入断点,此时你需要对依赖属性的值进行监听。

那如何监听呢?可以使用 DependencyPropertyDescriptor 类提供的一些方法。

比如:

public static DependencyPropertyDescriptor FromProperty(DependencyProperty dependencyProperty, Type targetType);
public override void AddValueChanged(object component, EventHandler handler);

DependencyPropertyDescriptor.FromProperty(MyProperty, typeof(依赖属性所属类型)).AddValueChanged(依赖属性所属实例,事件句柄);

这样就可以监听了依赖属性的变化了。

posted @ 2022-02-11 11:38  RafaelLxf  阅读(715)  评论(0)    收藏  举报