我有一个 ViewModelBase 类,如下所示:
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public static event PropertyChangedEventHandler GlobalPropertyChanged = delegate { };
public static void OnGlobalPropertyChanged(string propertyName, Type className)
{
GlobalPropertyChanged(className,new PropertyChangedEventArgs(propertyName));
}
}
现在,我有另一个名为 GroupViewModel 的 viewModel,它继承了 ViewModelBase:
public class GroupViewModel : ViewModelBase
{
public GroupsViewModel()
{
CurrentGroup = new Group();
}
private static Group _currentGroup;
public static Group CurrentGroup
{
get
{
return _currentGroup;
}
set
{
_currentGroup = value;
OnGlobalPropertyChanged("CurrentGroup", typeof(Group));
}
}
}
现在在 Groups.xaml 页面中:
<Grid DataContext="{Binding CurrentGroup}">
.....
.....
<TextBlock Text="{Binding GroupName, TargetNullValue=''}" />
.....
.....
</Grid>
我有另一个名为 MainWindowViewModel 的 ViewModel,我尝试将 CurrentGroup 保存到数据库,如下代码所示,然后我设置CurrentGroup = new Group();
但在 Group.xaml 中,TextBox 的文本未清除:
Group group = GroupViewModel.CurrentGroup;
db.Groups.Add(group);
db.SaveChanges();
GroupViewModel.CurrentGroup = new Group();
Update:
如果我在 GroupsViewModel 中使用以下代码,输出将符合预期。我的意思是当静态属性更改时视图会更新。
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged
= delegate { };
private static void NotifyStaticPropertyChanged(string propertyName)
{
StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}
如果我在 ViewModelBase 中使用相同的代码(请注意 GroupsViewModel 继承 ViewModelBase),则当静态属性值更改时,视图不会更新。另外,在这种情况下,我已将 NotifyStaticPropertyChanged 标记为公共,以避免编译时错误,例如有关保护级别的错误。