Domanda

I have a ViewModel like this:

public class ColorViewModel : INotifyPropertyChanged
{
    private SolidColorBrush colorBrush;

    public SolidColorBrush ColorBrush
    {
        get
        {
            return colorBrush;
        }
        set
        {
            if (value != colorBrush)
            {
                colorBrush = value;
                NotifyPropertyChanged("ColorBrush");
            }
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

and inside the MainViewModel I have defined it:

public ColorViewModel AppColor { get; set; }

and used it across the app:

<Grid x:Name="LayoutRoot" Loaded="LayoutRoot_Loaded">
    <StackPanel Background="{Binding AppColor.ColorBrush}" Height="240">
    </StackPanel>
</Grid>

it works fine. But the problem: when I try to change the value, it it doesn't appear and the element which is using it, still shows the old value. what is wrong?

App.ViewModel.AppColor = newColor;
È stato utile?

Soluzione

Because you defined AppColor as

public ColorViewModel AppColor { get; set; }

when you assing a new value to AppColor, notbody gets notified. Make the MainViewModel also implement INotifyPropertyChanged and change AppColor declaration to

private ColorViewModel appColor;

public ColorViewModel AppColor
{
    get
    {
        return appColor;
    }
    set
    {
        if (value != appColor)
        {
            appColor= value;
            NotifyPropertyChanged("AppColor");
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top