更改模型后刷新ViewModel所有属性上的数据绑定的好方法 [英] Good way to refresh databinding on all properties of a ViewModel when Model changes
问题描述
如果我更新ViewModel包装的Model对象,对我ViewModel公开的所有模型属性触发属性更改通知的好方法是什么?
If I update the Model object that my ViewModel wraps, what's a good way to fire property-change notifications for all the model's properties that my ViewModel exposes?
我正在按照MVVM模式开发WPF客户端,并尝试处理从服务到视图中显示的数据的传入更新.当客户端收到更新时,该更新以我用作模型的DTO的形式出现.
I'm developing a WPF client following the MVVM pattern, and am attempting to handle incoming updates, from a service, to data being displayed in my Views. When the client receives an update, the update appears in the form of a DTO which I use as a Model.
如果此模型是对View中显示的现有模型的更新,则我希望关联的ViewModel更新其数据绑定属性,以便View反映更改.
If this model is an update to an existing model being shown in the View, I want the associated ViewModel to update its databound properties so that the View reflects the changes.
让我举例说明.考虑我的模型:
class FooModel
{
public int FooModelProperty { get; set; }
}
包装在ViewModel中:
class FooViewModel
{
private FooModel _model;
public FooModel Model
{
get { return _model; }
set
{
_model = value;
OnPropertyChanged("Model");
}
}
public int FooViewModelProperty
{
get { return Model.FooModelProperty; }
set
{
Model.FooModelProperty = value;
OnPropertyChanged("FooViewModelProperty");
}
}
问题:
当更新的模型到达时,我设置ViewModel的Model属性,如下所示:
When an updated model arrives, I set the ViewModel's Model property, like so:
instanceOfFooVM.Model = newModel;
这会导致触发 OnPropertyChanged("Model")
,但不会触发 OnPropertyChanged("FooViewModelProperty")
,除非我从 Model显式调用后者代码>的二传手.因此,当我更改模型时,绑定到
FooViewModelProperty
的View不会更新以显示该属性的新值.
This causes OnPropertyChanged("Model")
to fire, but not OnPropertyChanged("FooViewModelProperty")
, unless I call the latter explicitly from Model
's setter. So a View bound to FooViewModelProperty
won't update to display that property's new value when I change the Model.
为每个公开的Model属性显式调用 OnPropertyChanged
显然不是一个理想的解决方案,也没有采用 newModel
并遍历其属性来一次更新ViewModel的属性,一一.
Explicitly calling OnPropertyChanged
for every exposed Model property is obviously not a desirable solution, and neither is taking the newModel
and iterating through its properties to update the ViewModel's properties one-by-one.
解决这个问题的更好的方法是更新整个模型,并需要为其所有公开的属性触发更改通知?
What's a better approach to this problem of updating a whole model and needing to fire change notifications for all its exposed properties?