简体   繁体   中英

Binding nested properties with MVVM Light

I'm having difficulty understanding how to bind to nested properties of an exposed model in a viewmodel using MVVM Light.

I have the following set up and the 'StreetAddress' component is not updating when a service updates the Address:

Address Model:

public class Address : ObservableObject
{
    private uint _streetNumber;

    public uint StreetNumber
    {
        get
        {
            return _streetNumber;
        }
        set
        {
            Set(ref _address, value, nameof(StreetNumber));
        }
    }
}

Person Model:

public class Person : ObservableObject
{
    private Address _address;

    public Address Address
    {
        get
        {
            return _address;
        }
        set
        {
            Set(ref _address, value, nameof(Address));
        }
    }
}

QueryPerson View Model:

public class QueryPersonViewModel : ViewModelBase
{
    public Person QueriedPerson { get; set; }

    public Address QueriedPersonAddress
    {
        get
        {
            return QueriedPerson.Address
        }
    }
    ...
}

QueryPerson View snippet:

<Grid DataContext="{Binding QueriedPersonAddress}">
    ...
    <TextBox Text="{Binding StreetNumber, Mode=OneWay}" />
</Grid>

Does the pattern above adhere to MVVM best practices? Is there a better way to bind to nested properties from the view? What would be the reason for the TextBox text to not be updated if the Address setter is called?

Property change notification doesn't propagate up the chain like that. When Address is changed only the things that are actually watching Address will be notified, not the things that are watching it's parent QueriedPerson. To fix this, remove the binding from your Grid and specify the full path in the TextBox binding:

<Grid>
    ...
    <TextBox Text="{Binding QueriedPerson.StreetNumber, Mode=OneWay}" />
</Grid>

If you absolutely need that Grid binding then you can put it back in but you'll have to add a RelativeBinding to the TextBox which binds to the Grid's parent's DataContext instead (ie the QueryPersonViewModel).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM