如何订阅改变的DependencyProperty?DependencyProperty

2023-09-03 20:27:06 作者:傲世小狂徒

可能重复:   听依赖属性修改

Possible Duplicate: Listen to changes of dependency property

对不起我的英语水平。

我需要创建一个可以订阅改变的DependencyProperty类,并根据此属性的新值来执行某些操作。

I need to create a class that could subscribe to change DependencyProperty, and depending on the new value of this property to perform some action.

这样的:

MyClass obj = new MyClass();
obj.Subscribe(TextBox.TextProperty, myTextBox);

我怎样才能做到这一点?

How can I do this?

推荐答案

下面是做它,使用得心应手DependencyPropertyDescriptor类的一种方式。

Here is one way of doing it, using the handy DependencyPropertyDescriptor class.

 var pd = DependencyPropertyDescriptor.FromProperty(TextBox.TextProperty, typeof(TextBox));
 pd.AddValueChanged(myTextBox, OnTextChanged);


 private void OnTextChanged(object sender, EventArgs e)
 {
     ...
 }