Communication between two viewmodels

前端 未结 2 1556
Happy的楠姐
Happy的楠姐 2021-02-06 13:09

I\'m newbie in MVVM design pattern, and I have these viewmodels :

ClassAViewModel

public class ClassAViewModel : INotifyPro         


        
相关标签:
2条回答
  • 2021-02-06 13:42

    I agree with other commenters that the mediator/pub-sub/event aggregator/messenger is a good way to go. If you're not using an MVVM framework with a built-in solution, then I recommend this simple approach that takes advantage of the Reactive extensions:

    public class EventPublisher : IEventPublisher
    {
        private readonly ConcurrentDictionary<Type, object> subjects
            = new ConcurrentDictionary<Type, object>();
    
        public IObservable<TEvent> GetEvent<TEvent>()
        {
            var subject =
                (ISubject<TEvent>) subjects.GetOrAdd(typeof (TEvent),
                            t => new Subject<TEvent>());
            return subject.AsObservable();
        }
    
        public void Publish<TEvent>(TEvent sampleEvent)
        {
            object subject;
            if (subjects.TryGetValue(typeof(TEvent), out subject))
            {
                ((ISubject<TEvent>)subject)
                    .OnNext(sampleEvent);
            }
        }
    }
    

    That's your whole event aggregator. Pass an instance of it into each view model, and store it as a reference. Then create a class to store your event details, let's say "ValueChangedEvent":

    public class ValueChangedEvent
    {
        public int Value
        {
            get { return _value; }
        }
        private readonly int _value;
    
        public ValueChangedEvent(int value)
        {
            _value = value;
        }
    }
    

    Publish like this from the first view model:

    set
    {
        _nbre = value;
        PropertyChanged(this, new PropertyChangedEventArgs("Nbre"));
        _eventPublisher.Publish(new ValueChangedEvent(value));
    }
    

    Subscribe in the other class using GetEvent:

    public class ClassBViewModel: INotifyPropertyChanged, IDisposable
    {
        private readonly IDisposable _subscriber;
    
        public ClassBViewModel(IEventPublisher eventPublisher)
        {
            _subscriber = eventPublisher.Subscribe<ValueChangedEvent>(next => 
            {
                IsBiggerthanFive = next.Value > 5;
            });
        }
    
        public void Dispose()
        {
            _subscriber.Dispose();
        }
    }
    
    0 讨论(0)
  • 2021-02-06 14:01

    A messenger service is a solution. MVVM Light Toolkit has an implementation of this. What you can do with it, is listen to a specific type of message in your viewmodel and handle it through the messenger. http://www.mvvmlight.net/

    0 讨论(0)
提交回复
热议问题