簡體   English   中英

當其他屬性更改時更新屬性

[英]Updating a property when a different property changes

我有一些XAML

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

兩者都應在相同的屬性更改事件IsRunning上更新到目前為止,我有三個屬性, ButtonBackgroundLabelBackgroundIsRunning其中IsRunning明確為所有三個觸發了OnNotifyPropertyChanged 如果我決定添加一個應在同一觸發器上更新的新屬性,這將很繁瑣且容易出現錯誤。

當更改其他屬性時,是否可以指示數據綁定獲取屬性的值? 也許像<Button Background="{Binding ButtonBackground, Source=IsRunning} />

如果您的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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM