17

Possible Duplicate:
Listen to changes of dependency property

Excuse me for my English.

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.

Like this:

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

How can I do this?

Community
  • 1
  • 1
Kovpaev Alexey
  • 1,725
  • 6
  • 19
  • 38

1 Answers1

34

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)
 {
     ...
 }
Marty
  • 7,464
  • 1
  • 31
  • 52
  • 16
    This approach causes memory leaks (see http://agsmith.wordpress.com/2008/04/07/propertydescriptor-addvaluechanged-alternative/) – Ilya Serbis Jul 22 '13 at 09:52
  • 4
    No leaks if handler removed via RemoveValueChanged(), or if the objects live as long as the process to start with. Use judiciously. – Vimes Jun 06 '19 at 16:29