属性更改未生效,MVVM

时间:2013-12-24 16:03:34

标签: c# mvvm windows-phone-8 windows-phone windows-phone-7.1

我有一个像这样的ViewModel:

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));
        }
    }
}

MainViewModel里面我定义了它:

public ColorViewModel AppColor { get; set; }

并在整个应用中使用它:

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

它工作正常。但问题是:当我尝试更改值时,它不会出现,并且正在使用它的元素仍显示旧值。怎么了?

App.ViewModel.AppColor = newColor;

1 个答案:

答案 0 :(得分:3)

因为您将AppColor定义为

public ColorViewModel AppColor { get; set; }

当您向AppColor分配新值时,不会收到通知。使MainViewModel也实现INotifyPropertyChanged并将AppColor声明更改为

private ColorViewModel appColor;

public ColorViewModel AppColor
{
    get
    {
        return appColor;
    }
    set
    {
        if (value != appColor)
        {
            appColor= value;
            NotifyPropertyChanged("AppColor");
        }
    }
}