Steven Deam
Steven Deam

Reputation: 577

WPF: Run Code when DependencyProperty Is Changed

In a simple user control I want to be able to run code any time that a dependency property changes.

    public static readonly DependencyProperty Text1Property =
    DependencyProperty.Register("Text1", typeof(string), 
        typeof(BasicControl));

    public string Text1
    {
        get { return GetValue(Text1Property).ToString(); }
        set
        {                
            SetValue(Text1Property, value.ToString());
            OnPropertyChanged("Text2");
        }
    }

Text2 in this case is another property that is derived from Text1 and displayed on the UI.

When running this the function is never reached. How can I get the code to run every time that a dependency property is changed?

Upvotes: 3

Views: 2858

Answers (3)

Aaron Thomas
Aaron Thomas

Reputation: 5281

Resist the temptation to use the set accessor for logic, when implementing a property to use the dependency property registration!

In other words, the set accessor only gets called if the property is set in procedural code. WPF calls SetValue directly when the property is set with XAML, data binding, etc. That is why the function isn't being reached... and it's why King King mentioned that what you have is simply a .NET property wrapper in his answer above.

A solution could be to run a trigger when the property is changed. Check out this MSDN article for more info, options, and examples.

Upvotes: 2

huoxudong125
huoxudong125

Reputation: 2056

@King's Answer is good,I want to add some info you should to know:

  • if you just want to back a property by dp and provide a default value, use PropertyMetadata,

    • if you want to specify animation behavior, use UIPropertyMetadata,

    • but if some property affects wpf framework level stuffs eg element layout, parent layout or databinding, use FrameworkPropertyMetadata.

Details you can check on msdn http://msdn.microsoft.com/en-us/library/ms751554.aspx

Upvotes: 2

King King
King King

Reputation: 63387

Clr property is just a wrapper of DependencyProperty, it's usually be by-passed unless you get/set the property directly in code behind. To handle something when the property is changed, you need to provide a PropertyMetadata containing some property changed callback, something like this:

public static readonly DependencyProperty Text1Property =
DependencyProperty.Register("Text1", typeof(string), 
    typeof(BasicControl), new PropertyMetadata(text1Changed));
//the text1Changed callback
static void text1Changed(DependencyObject o, DependencyPropertyChangedEventArgs e){
     var bc = o as BasicControl;
     if(bc != null) bc.OnPropertyChanged("Text2");
}

Upvotes: 3

Related Questions