首页 文章

模型没有实现INotifyPropertyChanged

提问于
浏览
3

在MVVM模式的上下文中,当Models没有实现INotifyPropertyChanged接口时,如何构建ViewModel?

我喜欢让我的模型尽可能简单,并且只为了绑定目的而实现INotifyPropertyChanged接口似乎是不必要的复杂性 . 这就是为什么我大多数时候都需要我的VM来包装模型属性,如下例所示:

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");
}

请分享您的想法,谢谢 .

1 回答

  • 0

    将您的成员声明为虚拟并使用类似Castle Dynamic Proxy的内容自动注入更改通知:

    http://ayende.com/blog/4106/nhibernate-inotifypropertychanged

    在数据层中创建模型时必须小心使用,因为它完全返回一个新实例 . 您的数据库代码会认为对象已更改并再次将其序列化,这将对性能产生巨大影响 . 幸运的是,所有优秀的ORM都为您提供了在创建时替换类包装器的机制 .

相关问题