【发布时间】:2012-04-13 10:49:15
【问题描述】:
对于是否应该在模型中实现INotifyPropertyChanged 似乎存在相互矛盾的想法。我认为它应该在 ViewModel 中实现,但我不知道它是如何实现的。在 stackoverlow.com(In MVVM model should the model implement INotifyPropertyChanged interface?、In MVVM should the ViewModel or Model implement INotifyPropertyChanged?)上到处都提到了同样的想法,但我找不到任何例子来展示如何做到这一点。
假设我有一个模型 Person:
Public Person {
public int Age { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public void NameChange( string newName );
}
我将如何实现 ViewModel 以使 Age、FirstName 或 LastName 中的更改都被识别?
Public PersonViewModel : INotifyPropertyChanged {
Person _person;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string propertyName) {
if(this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
//ctor, Properties, etc...
}
编辑 - 澄清:
那么在不更改 Person 模型的情况下如何修改 ViewModel 以获得更新通知?
这可能吗?如果没有,那些订阅“模型中的 INPC 是 baaaad”的人如何获得模型变化的通知?
【问题讨论】:
-
作为一个实际问题,在模型内启动的各个字段的更改多久会发生一次?
-
我不熟悉C#,但是你能用观察者设计模式来处理这个吗?
-
@Rich - 我没有具体的型号。我编写了实现 INotifyPropertyChanged 的模型,但总感觉不对。我读过很多人也觉得它是错误的,所以我的问题主要是弄清楚那些人是如何管理他们的模型的。
-
@Bwalks 我曾考虑过一个 ObservableCollection,但又一次由模型来实现 ObservableCollection。在我看来,这与 INotifyPropertyChanged 几乎相同,因为模型必须实现一些让消费者知道变化的东西。