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

后端 未结 1 697
灰色年华
灰色年华 2020-12-24 06:22

I have a WPF/Entity Framework (4.0) project with many objects. I\'d like to build the application so that that I can have object selection state shared across viewmodels.

相关标签:
1条回答
  • 2020-12-24 06:45

    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> {}
    
    0 讨论(0)
提交回复
热议问题