Concrete examples of state sharing between multiple viewmodels (WPF MVVM)

A typical way to achieve this is to use a messenger to publish a CarSelected message that details the selected car. Zero or more ViewModels can subscribe to the CarSelected message. ViewModels that are interested in the currently selected car can listen for the message and then act accordingly.

The messenger approach provides a clean decoupled design where publishers and subscribers have no dependencies on each other so can easily evolve independently – they just need to know about the car message. Messengers are an implementation of the mediator pattern.

In Prism the messenger is the EventAggregator and is used for publishing and subscribing to messages.

Update

Apart from the architectural advantages the EventAggregator brings, it also implements weak events to prevent memory leak issues with subscribers that do not explicitly unsubscribe.

Please see the following for EventAggregator documentation:

http://msdn.microsoft.com/en-us/library/ff649187.aspx

Prism:

http://compositewpf.codeplex.com/

Prism Example

public class ViewModel1
{
    private readonly IEventAggregator _eventService;
    private Car _selectedCar;

    public ViewModel1(IEventAggregator eventService)
    {
        _eventService = eventService;
    }

    //Databound property...
    public Car SelectedCar
    {
        set
        {
            _selectedCar = value;

            var msg = new CarSelectedMessage { Car = _selectedCar };

            _eventService.GetEvent<CarSelectedEvent>().Publish(msg);
        }
    }
}

public class ViewModel2
{
    public ViewModel2(IEventAggregator eventService)
    {
        eventService.GetEvent<CarSelectedEvent>().Subscribe(msg =>
        {
            //DoStuff with msg...
        });
    }
}

public class Car {}

public class CarMessage
{
    public Car Car { get; set; }
}

public class CarSelectedEvent : CompositePresentationEvent<CarMessage> {}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)