If the model implements INotifyPropertyChanged, how should the ViewModel register / unregister for the PropertyChanged event?

I have a model that implements INotifyPropertyChanged , and can be updated with a background business stream. The associated ViewModel also implements INotifyPropertyChanged . And their view is explicitly attached to the ViewModel. This view can be displayed in several places, and my goal is for all of them to be updated when the model changes.

I know that the ViewModel must be registered for the PropertyChanged event of the model. But I do not know when and where is the best place to register and unregister. Specially about unregistering, since I'm afraid to have hundreds of VM event handlers on the model for virtual machines / views that are no longer displayed.

Thanks in advance.

+7
source share
2 answers

Is it an absolute necessity to limit the representation directly not tied to the model?

You can open the model as a property in a virtual machine, and then associate it with your view, thereby not receiving an IMPC subscription 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 a DataContext ):

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

Update:

Maybe this will help you touch the events of PropertyChanged models in a "weak" way.

IWeakEventListener

Using centralized event scheduling WeakEventManager allows handlers to listen to garbage collected (or manually cleaned), even if the lifetime of the original object goes beyond the listeners.

which is used in

Josh Smith PropertyObserver

This, I hope, will solve your problem requiring an explicit rejection of registration?

+4
source

I circumvented this problem by connecting to event modeling at boot time and deleting them during unloading, the problem is that the view model can skip events if it is on the screen. Usually I just quickly update the data at boot time.

OnLoad - update virtual machine data from the model and intercept events. OnUnLoad - remove any hooks that you put in place.

0
source

All Articles