gpt4 book ai didi

c# - 模型未实现 INotifyPropertyChanged

转载 作者:行者123 更新时间:2023-11-30 18:28:21 25 4
gpt4 key购买 nike

在 MVVM 模式的上下文中,当模型未实现 INotifyPropertyChanged 接口(interface)时,如何构造 ViewModel?

我喜欢让我的模型尽可能简单,并且仅为绑定(bind)目的实现 INotifyPropertyChanged 接口(interface)似乎是不需要的复杂性。这就是为什么大多数时候我需要我的 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");
}
}
}

/* ... */
}

这将使绑定(bind)正常工作,包括双向绑定(bind)。

现在,如果命令执行具有复杂逻辑(影响不同对象的许多属性的值)的模型方法,会发生什么情况?该模型未实现 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");
}

请分享您的想法,谢谢。

最佳答案

声明您的成员是虚拟的,并使用诸如 CaSTLe Dynamic Proxy 之类的东西自动注入(inject)更改通知:

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

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

关于c# - 模型未实现 INotifyPropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25183641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com