What is a good way to bubble up INotifyPropertyCha

2019-03-24 15:22发布

问题:

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)

回答1:

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.



回答2:

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.



回答3:

Does your Address object implement INotifyPropertyChanged? If not, I think that would fix the issue that you are seeing.

Edit: Sorry, just noticed that you mentioned in your post that you tried this already. Have you tried subscribing to the PropertyChanged event of the Address object in your PersonViewModel? OnChanged, you could perform a PropertyChanged on your Address object.



回答4:

Check out PropertyChangedPropagator, it can handle dependencies on nested view models' properties including dynamically changeable nested view models: http://www.codeproject.com/Articles/775831/INotifyPropertyChanged-propagator