Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should one propagate events from one ViewModel to another ViewModel in MVVW?

I'm brand new to the MVVW pattern, so you'll have to forgive me if I'm asking a very basic question.

I have two ViewModels, we'll call them TreeViewViewModel and ListViewViewModel. TreeViewViewModel binds to an IsSelected property in its view. Whenever IsSelected changes, I need to inform ListViewViewModel so that it can update it's view.

After some research online, I've come across the EventAggregator which looks like it might be a good solution.

Is this the right solution? If so, how should I go about implementing this? Or, is there a better solution I should be considering? Below is a simplified version of how I think the EventAggregator might be integrated into the ViewModel publishing the event.

public class TreeViewViewModel : INotifyPropertyChanged
{
    public bool IsSelected
    {
        get { return _isSelected; }
        set
        {
            if (value == _isSelected)
                return;

            _isSelected = value;

            OnPropertyChanged("IsSelected");

            // Is this sane?
            _eventAggregator.GetEvent<TreeViewItemSelectedEvent>().Publish(value);
        }
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
like image 311
Nathanael Avatar asked Feb 15 '11 21:02

Nathanael


People also ask

Can a ViewModel contains other ViewModels?

Answers. It is perfectly right to have ViewModel contains ViewModel.

Can ViewModel have reference view?

Your ViewModels may not possess any references (member variables, properties, mutable/immutable fields) to any Views.

When to use ViewModels?

ViewModel is the right place to handle business logic in the UI layer. The ViewModel is also in charge of handling events and delegating them to other layers of the hierarchy when business logic needs to be applied to modify application data.


3 Answers

You can certainly use an event aggregator, but you don't need one for something as simple as this. You can simply have ListViewViewModel listen to TreeViewViewModel.PropertyChanged.

like image 140
Robert Rossney Avatar answered Oct 27 '22 17:10

Robert Rossney


EventAggregator is a good option and your code look correct to me. The other options would be SharedService or simply having direct reference from one viewmodel to another. Prism framework has a nice documentation on this topic: http://msdn.microsoft.com/en-us/library/ff921122(v=PandP.40).aspx

like image 20
Andrii Avatar answered Oct 27 '22 18:10

Andrii


Your other option is the mediator pattern, here is one example: http://marlongrech.wordpress.com/2009/04/16/mediator-v2-for-mvvm-wpf-and-silverlight-applications/

like image 1
Lugoues Avatar answered Oct 27 '22 17:10

Lugoues