Communication between two viewmodels

前端 未结 2 1557
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 subjects
            = new ConcurrentDictionary();
    
        public IObservable GetEvent()
        {
            var subject =
                (ISubject) subjects.GetOrAdd(typeof (TEvent),
                            t => new Subject());
            return subject.AsObservable();
        }
    
        public void Publish(TEvent sampleEvent)
        {
            object subject;
            if (subjects.TryGetValue(typeof(TEvent), out subject))
            {
                ((ISubject)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(next => 
            {
                IsBiggerthanFive = next.Value > 5;
            });
        }
    
        public void Dispose()
        {
            _subscriber.Dispose();
        }
    }
    

提交回复
热议问题