簡體   English   中英

如何將一個視圖正確綁定到多個ViewModel?

[英]How to bind a single view to multiple ViewModels properly?

我有一個像這樣的綁定視圖:

<TextBlock Text="{Binding Attribute1, Mode=TwoWay}" />
<TextBlock Text="{Binding Attribute2, Mode=TwoWay}" />

另外,我還有很多視圖模型,其中以某種方式調用了依賴屬性( NameOfficialName等),但是本質上它們是Attribute1 ,所以我想使用同一視圖將它們顯示給用戶。 所有綁定應該是雙向的。 我在考慮創建一個像這樣的臨時類:

public class AttributesInfo
{
   string Attribute1{ get; set; }
   // other attributes
}

並在每個視圖模型中公開一個屬性Attributes

return new AttributesInfo{ Attribute1 = Name, ... };
return new AttributesInfo{ Attribute1 = OfficialName, ... };

這將提供一個視圖:

<TextBlock Text="{Binding AttributesInfo.Attribute1, Mode=TwoWay}" />

現在,我正在考慮雙向綁定,並且我知道這是一個錯誤的解決方案。 有什么好嗎?

如果您使用所需的屬性屬性創建一個Interface並將其在不同的VM中實現,則更好。

例如

public interface IAttribute
{
   string Attribute1 {get; set;}
   .
   .
   .
}

public class someVM : IAttribute
{
  private string _name;
  public string Nam
  {
     get {return _name;}
     set
     {
        _name = value;
        NotifyPropertyChanged("Name");
                 }
  }

  public string Attribute1
  {
     get{return this.Name;}
     set
     {
        this.Name = value; 
        NotifyPropertyChange("Attribute1");
     }
  }
}

這樣,您的屬性將與屬性同步,並且您可以對所有VM使用相同的視圖。

暫無
暫無

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

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