【问题标题】:How to bind a single view to multiple ViewModels properly?如何正确地将单个视图绑定到多个 ViewModel?
【发布时间】:2014-07-23 13:54:23
【问题描述】:

我有一个视图,其绑定如下:

<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}" />

现在我正在考虑双向绑定,我明白这是一个错误的解决方案。有什么好的吗?

【问题讨论】:

  • 为什么没有一个包含两个子视图模型的“MainViewModel”?
  • 这些数据模型是不是视图模型(即使有很多微软提供的材料,也有很多关于差异的混淆......)。我可能会想念您在这里尝试做的事情,但我注意到您没有在数据模型中实现 INotifyPropertyChanged 接口(如果是这样的话),这是发出 UI 应该重绘的信号所必需的。好吧,或者使用带有 D.P 的 D.O。

标签: c# wpf silverlight mvvm


【解决方案1】:

如果您创建一个具有所需属性属性的接口并在不同的虚拟机中实现它会更好。

例如

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");
     }
  }
}

通过这种方式,您的属性将与属性同步,您可以对所有虚拟机使用相同的视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多