【发布时间】:2014-03-12 08:48:14
【问题描述】:
我有一个 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 的视图模型,它继承了 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();
更新:
如果我在 GroupsViewModel 中使用以下代码,则输出符合预期。我的意思是当静态属性更改时视图会更新。
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged
= delegate { };
private static void NotifyStaticPropertyChanged(string propertyName)
{
StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
}
如果我在 ViewModelBase 中使用相同的代码(请注意 GroupsViewModel 继承 ViewModelBase),那么当静态属性的值发生更改时,视图不会更新。在这种情况下,我还将 NotifyStaticPropertyChanged 标记为 public 以避免编译时错误,例如有关保护级别的错误。
【问题讨论】:
-
试用here提供的解决方案。
-
必须引发视图模型的属性更改事件,静态成员不是实例的成员。
-
@RohitVats 好的,我会尝试并告诉你。
-
@Silvermind 必须引发视图模型的属性更改事件是什么意思?
-
@RohitVats 我无法打开您提供的链接。它只是继续加载.......