![](/img/trans.png)
[英]How to bind multiple viewmodels to a single xaml file in MVVM wpf?
[英]How to bind a single view to multiple ViewModels properly?
我有一个像这样的绑定视图:
<TextBlock Text="{Binding Attribute1, Mode=TwoWay}" />
<TextBlock Text="{Binding Attribute2, Mode=TwoWay}" />
另外,我还有很多视图模型,其中以某种方式调用了依赖属性( Name , OfficialName等),但是本质上它们是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.