更改模型后刷新ViewModel所有属性上的数据绑定的好方法 [英] Good way to refresh databinding on all properties of a ViewModel when Model changes

查看:70
本文介绍了更改模型后刷新ViewModel所有属性上的数据绑定的好方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我更新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?

推荐答案

根据

PropertyChanged事件可以通过使用null或String.Empty作为PropertyChangedEventArgs中的属性名称来指示对象上的所有属性都已更改.

The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs.

这篇关于更改模型后刷新ViewModel所有属性上的数据绑定的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆