棱镜 BindableBase.SetProperty() [英] Prism BindableBase.SetProperty()
问题描述
我正在开发基于 BindableBase 的 ViewModel.这个 VM 拥有一个域模型的实例.VM 公开了一个属性,比如 Name,我不想使用本地存储(即 VM 中的存储),而是委托给模型对象的属性.我想使用 SetProperty(),但存储引用不能是属性.我是否必须实现 INotifyPropertyChanged my self ?以这种方式委托给模型是一个好主意吗?是否可以扩展 BindableBase(或要添加的团队)来解决这个问题?
I am developing a ViewModel based on BindableBase. This VM holds an instance of a domain model. The VM exposes a property, say Name from which I want to not use local storage (i.e. storage in VM), but rather delegate to the model object's property. I would like to use SetProperty(), but the storage reference cannot be a property. Do I have to implement INotifyPropertyChanged my self ? Is it at all a good idea to delegate to the model this way ? Would it be possible to extend BindableBase (or team to add) to cover for this ?
推荐答案
因此,首先您必须选择构建 VM 和模型的方式.正如您所提到的,有几个选项.我推荐的最简单和最简单的方法是将您的模型作为属性公开,然后将您的视图绑定到模型属性:
So first you must chose how you will architect your VMs and Models. As you mentioned, there are a few options. The easiest and the way I recommend, is to just expose your Model as a property and then bind your View to the model properties:
public class MyViewModel : BindableBase
{
private Person _myPerson;
public Person Person
{
get { return _myPerson; }
set { SetProperty(ref _myPerson, value); }
}
}
如果您不想这样做,而是想包装每个单独的模型属性,您可以这样做.
If you don't want to do that and would rather wrap each individual model property, you would do it like this.
public class MyViewModel : BindableBase
{
private Person _myPerson;
private string _name;
public string Name
{
get { return _myPerson.Name; }
set { _myPerson.Name = value }
}
}
请记住,您的 Person 模型对象仍然需要实现 INPC.
Keep in mind, your Person model object still has to implement INPC.
如果您无法控制您的模型并需要它们来实现 INPC,您可以尝试使用 IL 编织,或为您的模型创建一个外观/装饰器并单独包装它们.
If you don't have control over your models and need them to implement INPC, you could try to use IL weaving, or create a façade/decorator for your models and wrap them individually.
public class MyPersonFacade : BindableBase
{
private Person _myPerson;
private string _name;
public string Name
{
get { return _myPerson.Name; }
set
{
_myPerson.Name = value;
OnPropertyChanged();
}
}
}
然后将其用作 VM 中的模型.
Then use this as your Model in your VM.
这篇关于棱镜 BindableBase.SetProperty()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!