[英]WPF - Raise Event from UserControl ViewModel
I have a WPF application that uses MVVM 我有一个使用MVVM的WPF应用程序
The MainWindowViewModel has references to other ViewModels like so:- MainWindowViewModel引用了其他ViewModel,例如:
this.SearchJobVM = new SearchJobViewModel();
this.JobDetailsVM = new JobDetailsViewModel();
this.JobEditVM = new JobEditViewModel();
I have a Label on the MainWindow called StatusMessage which is bound to a string property on the MainWindowViewModel 我在MainWindow上有一个名为StatusMessage的标签,该标签绑定到MainWindowViewModel上的字符串属性
I want to be update to change this message on any of the other view models and have it updated on the UI 我想进行更新以在任何其他视图模型上更改此消息,并在用户界面上对其进行更新
Do I need to Raise an Event from the other ViewModels to the MainWindowViewModel? 我是否需要将事件从其他ViewModel引发到MainWindowViewModel?
How do I go about achieving this? 我该如何实现这一目标?
The cleanest way I can think of you doing this (and I do it myself sometimes) is to pass a reference to your MainWindowViewModel into these sub-view-models, ie: 我可以想到的最干净的方法(有时是我自己做)是将对MainWindowViewModel的引用传递到这些子视图模型中,即:
this.SearchJobVM = new SearchJobViewModel(this);
this.JobDetailsVM = new JobDetailsViewModel(this);
this.JobEditVM = new JobEditViewModel(this);
Then from one of these sub-view-models, provided you have stored your reference in a property named MainViewModel, you could do something like: 然后从这些子视图模型之一中,假设您已将引用存储在名为MainViewModel的属性中,则可以执行以下操作:
MainViewModel.StatusMessage = "New status";
And if your VMs support INotifyPropertyChanged then everything will automatically update. 而且,如果您的VM支持INotifyPropertyChanged,则所有内容都会自动更新。
I think it depends on how much you want the viewmodels to be independent of each other; 我认为这取决于您希望视图模型彼此独立的程度。
The solution of user3690202, allthough viable, does create a dependency of the child viewmodels (SearchJobViewModel, etc...) on the MainViewModel. user3690202的解决方案尽管可行,但确实在MainViewModel上创建了子视图模型(SearchJobViewModel等)的依赖项。
And because your viewmodels probably allready implement INotifyPropertyChanged, you could expose the message on the childviewmodels aa property and make the MainViewModel listen for changes on the childviewmodels. 并且由于您的视图模型可能已经实现INotifyPropertyChanged,因此您可以在childviewmodels的aa属性上公开消息,并使MainViewModel侦听childviewmodels上的更改。
Thus, you would get something like the followin: 因此,您将获得类似以下内容的信息:
class SearchJobViewModel : INotifyPropertyChanged
{
string theMessageFromSearchJob;
public string TheMessageFromSearchJob
{
get { return theMessageFromSearchJob; }
set {
theMessageFromSearchJob = value;
/* raise propertychanged here */ }
}
}
And then in the MainViewModel: 然后在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.