我有三个ViewModel: - MainViewModel, - NavigatorViewModel, - ProjectViewModel。
在MainViewModel中,我有一个名为CurrentProject的属性,类型为ProjectViewModel:
public ProjectViewModel CurrentProject
{
get
{
return _currentProject;
}
set
{
if (_currentProject == value)
{
return;
}
_currentProject = value;
RaisePropertyChanged("CurrentProject");
}
}
在NavigatorViewModel中,我还有一个属性CurrentProject
public ProjectViewModel CurrentProject { get { return ViewModelLocator.DesktopStatic.CurrentProject; } }
我使用MVVM灯。如果MainViewModel中的属性CurrentProject已更改,则View NavigatorView不会收到通知。
如何让NavigatorView知道该属性已更改?
答案 0 :(得分:0)
作为一个设计问题,我建议不要使用静态Singleton模式。您可以使用Messenger
类发送消息。
但是,要解决当前问题,您需要针对该属性响应Singleton上的PropertyChanged
事件:
public class NavigatorViewModel : INotifyPropertyChanged
{
public NavigatorViewModel()
{
// Respond to the Singlton PropertyChanged events
ViewModelLocator.DesktopStatic.PropertyChanged += OnDesktopStaticPropertyChanged;
}
private void OnDesktopStaticPropertyChanged(object sender, PropertyChangedEventArgs args)
{
// Check which property changed
if (args.PropertyName == "CurrentProject")
{
// Assuming NavigatorViewModel also has this method
RaisePropertyChanged("CurrentProject");
}
}
}
此解决方案侦听Singleton属性的更改,并将更改传播给NavigatorViewModel
的侦听器。
警告: NavigatorViewModel
中的某个位置需要取消该事件,否则可能会造成内存泄漏。
ViewModelLocator.DesktopStatic.PropertyChanged -= OnDesktopStaticPropertyChanged;