Implementing INotifyPropertyChanged for nested properties
How do I get the SET method of the Person object inside the ViewModel to be called when Person.Address.StreetOne is changed???
Why do you want to do this? It should not be required - you only need the StreetOne
property changed event to fire.
Do I need to flatten my data so SteetOne is inside Person and not Address??
If you want to actually cause this to trigger, you don't need to flatten it (though that is an option). You can subscribe to the Address
's PropertyChanged
event within your Person class, and raise the event for "Address" within Person
when it changes. This shouldn't be necessary, however.
if you want the viewmodel SET to be called you could create a street property
public class MyViewModel
{
//constructor and other stuff here
public string Street{
get { return this.Person.PrimaryAddress.StreetOne; }
set {
if ( this.Person.PrimaryAddress.StreetOne!= value ) {
this.Person.PrimaryAddress.StreetOne = value;
OnPropertyChanged( "Street" );
}
}
}
xaml
<TextBox Text="{Binding Street, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged />
but this solution has its drawbacks. i go with Reeds answer in my projects
While adding 'pass-through' properties to your ViewModel is a fine solution, it can quickly become untenable. The standard alternative is to propagate changes as below:
public Address PrimaryAddress {
get => _primaryAddress;
set {
if ( _primaryAddress != value )
{
//Clean-up old event handler:
if(_primaryAddress != null)
_primaryAddress.PropertyChanged -= AddressChanged;
_primaryAddress = value;
if (_primaryAddress != null)
_primaryAddress.PropertyChanged += AddressChanged;
OnPropertyChanged( "PrimaryAddress" );
}
void AddressChanged(object sender, PropertyChangedEventArgs args)
=> OnPropertyChanged("PrimaryAddress");
}
}
Now change notifications are propagated from Address to person.
Edit: Moved handler to c# 7 local function.