Generally raising PropertyChangeNotification change property in different class

152 views Asked by At

I have two classes:

  1. ViewModelA
  2. MainViewModel.

Both implement INotifyPropertyChanged interface.

MainViewModel holds an observable collection of ViewModelA objects. I need a change of a certain property "X" in any ViewModelA class to trigger a PropertyChangeNotification in property "Y" in MainViewModel.

Question 1: What is the common practice to implement this?

Question 2: Is listening to CollectionChanged on the ObservableCollection and attaching/removing an event handler (that would check if the "X" property was changed and if yes would trigger the "Y" property change notification) a bad practice? If yes why?

2

There are 2 answers

0
BendEg On

I would implement my own event in ViewModelA, and subscribe it when creating a new ViewModelA in MainViewModel. The event will be called in ViewModelA, if some thing habbend.

0
Lawrence On

Just to clarify the problem: you wish to callback to the parent view model when a property of a child view model (or in your particular case an element of a collection of child view models) changes.

In your particular case you want to to call the INotifyPropertyChanged event with some property on the main view model to update the UI.

Essentially, you are looking at some derivation of the Observer Design Pattern, whereby you somehow "listen" for changes on the child view model and the parent is notified. Two implementations of this pattern readily exist for you to consume:

  1. Events: As somebody else has already answered in this question - you could create an event on the child view model, and subscribe to this event from the parent directly. Personally, I shy away from defining events on my view models where possible - for me a view model is a logical representation of the view, and having a public event on the view model interface seems to go against the grain.

  2. Event Aggregator: Using an Event Aggregator (such as the one provided by PRISM) allows you to subscribe to messaged on the parent view model that are fired out of the child view model. The price you pay for not having to have a public event defined on your child view model is a dependency on an implementation of IEventAggregator. I like this approach as it separates out the concerns of the parent and child view models, and the interaction between them. One word of warning is that use of the event aggregator is open to abuse, and if you use it carelessly it can make it hard to track all the messages that are flying around your application.