如果模型实现INotifyPropertyChanged,应该怎么视图模型注册/注销的PropertyChanged事件?模型、视图、事件、INotifyPropertyChanged

2023-09-04 02:39:20 作者:风月不等闲

我有一个实现 INotifyPropertyChanged的模型,它可能会通过后台的业务线进行更新。其相关视图模型还实现了 INotifyPropertyChanged的。而他们显然观结合到视图模型。此视图可以显示在多个地方,而我的目标是,所有的人都得到更新,当模型更改。

I have a Model which implements INotifyPropertyChanged and it may get updated by a background business thread. Its related ViewModel also implements INotifyPropertyChanged. And their View obviously binds to ViewModel. This View may be shown on multiple places, and my goal is that all of them get updated when the model changes.

我知道视图模型应该注册模型的PropertyChanged 事件。但我不知道何时何地是该注册和注销的最好的地方。特别关于注销的,因为我很害怕有以下几点作出的不再显示的型号为VM /意见数百虚拟机的事件处理程序的。

I know that ViewModel should register for PropertyChanged event of Model. But I don't know when and where is the best place for this registering and deregistering. Specially about the deregistering, since I'm scared of having hundreds of VM event handlers on the Model for the VM/views that are not shown anymore.

在此先感谢。

推荐答案

它是绝对必要为你限制视图不直接绑定到模型?

Is it an absolute necessity for you to limit the View not directly bind to the Model?

您可以公开的模型作为虚拟机的属性,然后让你的视图直接绑定到它,从而不具有VM订阅INPC从型号

You can expose the Model as a property on the VM and then have your View directly bind to it thereby not having the VM subscribe to INPC from Model

是这样的:

public class MyViewModel: INotifyPropertyChanged {
...

private MyModel _model;
public MyModel Model {
  get {
    return _model;
  }
  set {
    if (value == _model)
      return;
    value = _model;
    RaisePropertyChanged(() => Model);
  }
}
...

}

和在XAML(当 MyViewModel 的DataContext ):

and in xaml (when MyViewModel is the DataContext):

<TextBlock Text="{Binding Model.ModelProperty}" />

更新:

也许这是一些帮助窃听到模型的的PropertyChanged 事件弱时尚

Maybe this is of some help for tapping into the PropertyChanged events of Models in a "weak" fashion

IWeakEventListener

使用中央事件分派一个WeakEventManager的的使处理程序侦听器被垃圾收集(或手动清除)即使源对象生存期超出侦听器。

Using the central event dispatching of a WeakEventManager enables the handlers for listeners to be garbage collected (or manually purged) even if the source object lifetime extends beyond the listeners.

其用于

约什·史密斯的PropertyObserver

这应该有希望解决需要明确地注销了您的问题?

This should hopefully solve your issue of needing to explicitly un-register?