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)
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.
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.
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With