Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to bubble up INotifyPropertyChanged events through ViewModel properties with MVVM?

I'm trying to figure out the best way to bubble up PropertyChanged events from nested Properties in my ModelView. Say I have my ModelView PersonModelView which has a Property PersonModelView.Address. Address in turn has a property City. When I bind to City in my view, I would do something like {Binding Address.City}.

My problem is that even if Address implements INotifyPropertyChanged, the binding will not get updated because it is handling PropertyChanged on the PersonModelView, not Address. I think I have two options: (1) change the source of the binding (or change the DataContext) to the Address property or (2) have the PersonModelView handle PropertyChanged on the Address object and refire its own PropertyChanged with something like Address.City.

How are you guys solving this? (I'm using MVVM light toolkit at the mo, but am interested in any approaches)

like image 715
Geoff Avatar asked Oct 14 '10 12:10

Geoff


People also ask

Should ViewModel implement INotifyPropertyChanged?

You should always have the Model implement INotifyPropertyChanged and this is just a mistake which would be corrected if this were developed from a code example to an application.

Can a model implement INotifyPropertyChanged?

The standard MVVM approach is to implement INotifyPropertyChanged only on the ViewModel. The purpose is to refresh the appropriate bindings on the View when something changes in the ViewModel. However, this targets changes to the ViewModel by the View.

How do you implement INotifyPropertyChanged in WPF?

To implement INotifyPropertyChanged you need to declare the PropertyChanged event and create the OnPropertyChanged method. Then for each property you want change notifications for, you call OnPropertyChanged whenever the property is updated.

What is INotifyPropertyChanged used for?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .


2 Answers

If Address implements INotifyPropertyChanged and correctly raises PropertyChanged events on its City property then the binding should notice that the property it is bound to has changed.

like image 111
Jackson Pope Avatar answered Oct 02 '22 19:10

Jackson Pope


Here's a SO thread containing a solution on how to bubble up these notifications: When nesting properties that implement INotifyPropertyChanged must the parent object propogate changes?

However, IIRC WPF has the intelligence to automatically monitor Address for INotifyPropertyChanged notifications when a control's binding is set to Address.City without PersonViewModel needing to re-broadcast the Address object's update notifications.

like image 44
Ben Gribaudo Avatar answered Oct 02 '22 18:10

Ben Gribaudo