Raise Event from UserControl ViewModel

I have a WPF application that uses MVVM

The MainWindowViewModel has references to other ViewModels like so:-

            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

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?

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:

        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.StatusMessage = "New status";

And if your VMs support INotifyPropertyChanged then everything will automatically update.


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.

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.

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:

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;
    }
}
链接地址: http://www.djcxy.com/p/39544.html

上一篇: 基于MainWindow事件更新viewmodel

下一篇: 从UserControl ViewModel引发事件