[英]WPF - Raise Event from UserControl ViewModel
我有一个使用MVVM的WPF应用程序
MainWindowViewModel引用了其他ViewModel,例如:
this.SearchJobVM = new SearchJobViewModel();
this.JobDetailsVM = new JobDetailsViewModel();
this.JobEditVM = new JobEditViewModel();
我在MainWindow上有一个名为StatusMessage的标签,该标签绑定到MainWindowViewModel上的字符串属性
我想进行更新以在任何其他视图模型上更改此消息,并在用户界面上对其进行更新
我是否需要将事件从其他ViewModel引发到MainWindowViewModel?
我该如何实现这一目标?
我可以想到的最干净的方法(有时是我自己做)是将对MainWindowViewModel的引用传递到这些子视图模型中,即:
this.SearchJobVM = new SearchJobViewModel(this);
this.JobDetailsVM = new JobDetailsViewModel(this);
this.JobEditVM = new JobEditViewModel(this);
然后从这些子视图模型之一中,假设您已将引用存储在名为MainViewModel的属性中,则可以执行以下操作:
MainViewModel.StatusMessage = "New status";
而且,如果您的VM支持INotifyPropertyChanged,则所有内容都会自动更新。
我认为这取决于您希望视图模型彼此独立的程度。
user3690202的解决方案尽管可行,但确实在MainViewModel上创建了子视图模型(SearchJobViewModel等)的依赖项。
并且由于您的视图模型可能已经实现INotifyPropertyChanged,因此您可以在childviewmodels的aa属性上公开消息,并使MainViewModel侦听childviewmodels上的更改。
因此,您将获得类似以下内容的信息:
class SearchJobViewModel : INotifyPropertyChanged
{
string theMessageFromSearchJob;
public string TheMessageFromSearchJob
{
get { return theMessageFromSearchJob; }
set {
theMessageFromSearchJob = value;
/* raise propertychanged here */ }
}
}
然后在MainViewModel中:
this.SearchJobVM = new SearchJobViewModel();
this.SearchJobVM += SearchJobVM_PropertyChanged;
void SearchJobVM_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "TheMessageFromSearchJob")
{
this.StatusMessage = this.SearchJobVM.TheMessageFromSearchJob;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.