我有一些XAML
<Button Background="{Binding ButtonBackground}" />
<Label Background="{Binding LabelBackground}" />
两者都应该更新同一属性更改事件IsRunning
到目前为止,我有三个属性,ButtonBackground
,LabelBackground
和IsRunning
,IsRunning
明确触发所有三个OnNotifyPropertyChanged
。如果我决定添加一个应该在同一触发器上更新的新属性,这很麻烦且容易出错。
当不同的属性发生变化时,是否可以指示数据绑定获取属性的值?也许像<Button Background="{Binding ButtonBackground, Source=IsRunning} />
?
答案 0 :(得分:1)
如果您的IsRunning
属性是DependencyProperty
,那么您只需添加PropertyChangedCallback
处理程序即可。每次更新IsRunning
属性时都会调用此处理程序,因此您可以从那里设置其他属性:
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
}
如果它不是DependencyProperty
,那么您可以从设置器更新其他属性:
public bool IsRunning
{
get { return isRunning; }
set
{
isRunning = value;
NotifyPropertyChanged("IsRunning");
// Update your other properties here
}
}