Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

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.

Thanks in advance.

like image 961
n0ne Avatar asked May 02 '13 14:05

n0ne


1 Answers

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?

like image 55
Viv Avatar answered Nov 15 '22 09:11

Viv