我有一个像这样的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;
答案 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");
}
}
}