Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 963
Steven Deam Avatar asked Mar 21 '26 14:03

Steven Deam


1 Answers

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");
}
like image 147
King King Avatar answered Mar 23 '26 03:03

King King



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!