在MVVM模式下,当Models不实现INotifyPropertyChanged接口时,该如何构建ViewModel结构?
我喜欢保持我的Models尽可能简单,仅为了绑定目的实现INotifyPropertyChanged接口似乎是不必要的复杂性。这就是为什么大多数时候我需要我的VMs像以下示例一样包装模型属性:
class ViewModel : INotifyPropertyChanged
{
private Model model;
public int MyProperty
{
get { return model.MyProperty; }
set
{
if (value != model.MyProperty)
{
model.MyProperty = value;
// Trigger the PropertyChanged event
OnPropertyChanged("MyProperty");
}
}
}
/* ... */
}
这将使绑定正常工作,包括双向绑定。
现在,如果一个命令执行具有复杂逻辑的模型方法(影响不同对象的许多属性的值),会发生什么情况?该模型没有实现INotifyPropertyChanged,因此我们无法知道它已更新。唯一我想到的解决方案是使用消息传递(中介者模式)通知所有VM执行该方法,以便每个VM为每个可能受影响的属性触发PropertyChanged事件:
// Sample ICommand.Execute() implementation
public void Execute(object parameter)
{
var model = (Model)parameter;
model.VeryComplexMethod();
// Just an example, the string "VeryComplexMethodExecuted" is
// sent to all listening VMs. Those VMs will in turn fire the
// PropertyChanged event for each property that may have changed
// due to the execution of the complex model method.
Messaging.Broadcast("VeryComplexMethodExecuted");
}
请分享您的想法,谢谢。