如何订阅更改DependencyProperty?

Kov*_*xey 14 .net c# wpf dependency-properties

可能重复:
侦听依赖项属性的更改

对不起我的英语.

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

像这样:

MyClass obj = new MyClass();
obj.Subscribe(TextBox.TextProperty, myTextBox);
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Mar*_*ill 28

这是使用方便的DependencyPropertyDescriptor类的一种方法.

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


 private void OnTextChanged(object sender, EventArgs e)
 {
     ...
 }
Run Code Online (Sandbox Code Playgroud)

  • 此方法导致内存泄漏(请参阅http://agsmith.wordpress.com/2008/04/07/propertydescriptor-addvaluechanged-alternative/) (12认同)
  • 如果通过 RemoveValueChanged() 删除处理程序,或者对象的生命周期与进程开始时一样长,则不会发生泄漏。谨慎使用。 (3认同)