If a model implements INotifyPropertyChanged, how should ViewModel register/deregister for PropertyChanged event?

一笑奈何 提交于 2019-12-05 04:59:04

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

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

something like:

public class MyViewModel: INotifyPropertyChanged {
...

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

}

and in xaml (when MyViewModel is the DataContext):

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

Update:

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

IWeakEventListener

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.

which is used in

Josh Smith's PropertyObserver

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

I've gotten around this issue by hooking in to model events on load and removing them on unloaded, the problem here is that the view model can miss events if it's off the screen. I usually just refresh the data quickly on load.

OnLoad - Refresh the VM data from the model and hook events. OnUnLoad - remove any hooks that you've put in place.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!