且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-03 12:33:16

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

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?