簡體   English   中英

父屬性更改時嵌套屬性的 WPF 綁定更新通知

[英]WPF binding update notification for nested property when parent property changes

我有一個具有復雜屬性類型的 ViewModel,並希望將我的視圖綁定到此對象的嵌套屬性。

我的 ViewModel 正在實現INotifyPropertyChanged (或者確實BaseViewModel正在實現它)。 父屬性的類沒有實現INotifyPropertyChanged

類 Car 沒有實現INotifyPropertyChanged 但是我沒有更改屬性Manufacturer ,而是更改了MyCarProperty屬性,所以我希望OnNotifyPropertyChanged事件會觸發值更新?

當我更新父屬性的值時,嵌套屬性沒有更新。 你能告訴我如何實現這個功能嗎?

視圖模型

public class ViewModel : BaseViewModel
{
    private Car _myCarProperty;

    public Car MyCarProperty
    {
        get { return _myCarProperty; }
        set
        {
            if (value == _myCarProperty) return;

            _myCarProperty = value;
            OnPropertyChanged();
        }
    }
}

在視圖中綁定

<TextBlock Text="{Binding Path=MyCarProperty.Manufacturer}" />

當我更改MyCarProperty的值時,視圖不會更新。

謝謝你的幫助!

編輯: OnPropertyChanged() 實現

#region INotifyPropertyChanged

public event PropertyChangedEventHandler PropertyChanged;

[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

#endregion INotifyPropertyChanged

“類 Car 沒有實現 INotifyPropertyChanged。但我沒有更改屬性制造商,我更改了 MyCarProperty 屬性,所以我希望 OnNotifyPropertyChanged 事件會觸發值更新?”

不,它不會觸發值更新一個級別。 綁定不偵聽整個路徑的屬性更改,它們只偵聽綁定到的對象。

我在腦海中看到了幾個選項(按照我遇到這個的偏好順序):

  1. 綁定到汽車,而不是子屬性,並創建一個數據模板來顯示您想要的內容。
  2. 在需要時通過在其BindingExpression上調用 UpdateTarget 來手動啟動綁定。

我知道它看起來像有很多東西要學數據模板路線上,但我向你保證數據的模板將更加強大,可擴展性,可維護性和有用的證明比手動踢綁定,你在WPF更多的工作。 (另外,一旦你理解了它們,我認為它們實際上比手動踢綁定更少的工作)。

祝你好運!

接受的答案解釋了如何處理綁定源上的子屬性發生更改並且您希望更新視圖的情況 - 這不是問題所要問的。 WPF 實際上會響應從多個級別向下的更改,只要您通知指定路徑內更改的任何屬性的更改。

至於這個:

“類 Car 沒有實現 INotifyPropertyChanged。但我沒有更改屬性 Manufacturer ,我更改了 MyCarProperty 屬性,所以我希望 OnNotifyPropertyChanged 事件會觸發值更新?”

WPF 已經處理了這個問題。

在您的示例中, ViewModel是綁定源。 當您設置MyCarProperty (觸發NotifyPropertyChanged事件)時,WPF 將使用綁定源對象的綁定路徑重新評估綁定目標值 - 使用新的Manufacturer更新您的視圖。

我已經用一個簡單的 WPF 應用程序對此進行了測試——它也適用於非常深的嵌套路徑:

https://pastebin.com/K2Ct4F0F

<!-- When MyViewModel notifies that "MyCarProperty" has changed, -->
<!-- this binding updates the view by traversing the given Path -->
<TextBlock Text="{Binding Path=MyCarProperty.Model.SuperNested[any][thing][you][want][to][try][and][access].Name}" />

我不是 WPF 專家,但我認為這是因為您選擇了錯誤的路徑。

<TextBlock Text="{Binding Path=MyCarProperty, Value=Manufacturer}" />

更新:

<TextBlock Text="{Binding Source=MyCarProperty, Path=Manufacturer}" />

暫無
暫無

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

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