简体   繁体   中英

Updating a property when a different property changes

I have some XAML

<Button Background="{Binding ButtonBackground}" />
<Label Background="{Binding LabelBackground}" />

that both should update on the same property changed event IsRunning So far I have three properties, ButtonBackground , LabelBackground and IsRunning with IsRunning explicitly firing the OnNotifyPropertyChanged for all three. This is tedious and prone to bugs if I decide to add a new property that should update on the same trigger.

Is is possible to instruct the data binding to get the value of a property when a different property is changed? Maybe something like <Button Background="{Binding ButtonBackground, Source=IsRunning} /> ?

If your IsRunning property is a DependencyProperty , then you can just add a PropertyChangedCallback handler. This handler will be called every time that the IsRunning property is updated, so you can set your other properties from there:

public static readonly DependencyProperty IsRunningProperty = DependencyProperty.
Register("IsRunning", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(false, 
OnIsRunningChanged));

public bool IsRunning
{
    get { return (bool)GetValue(IsRunningProperty); }
    set { SetValue(IsRunningProperty, value); }
}

private static void OnIsRunningChanged(DependencyObject d, 
DependencyPropertyChangedEventArgs e) 
{
    // Update your other properties here
}

If it's not a DependencyProperty , then you can just update your other properties from the setter:

public bool IsRunning
{
    get { return isRunning; }
    set
    {
        isRunning = value;
        NotifyPropertyChanged("IsRunning");
        // Update your other properties here
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM