应该如何将事件从一个ViewModel传播到MVVM中的另一个ViewModel?

时间:2011-02-15 21:19:49

标签: wpf viewmodel eventaggregator

我是MVVW模式的新手,所以如果我问一个非常基本的问题你就不得不原谅我。

我有两个ViewModel,我们将它们称为TreeViewViewModel和ListViewViewModel。 TreeViewViewModel在其视图中绑定到IsSelected属性。每当IsSelected更改时,我都需要通知ListViewViewModel,以便它可以更新它的视图。

经过网上的一些研究,我遇到了EventAggregator,看起来它可能是一个很好的解决方案。

这是正确的解决方案吗?如果是这样,我该如何实施呢?或者,我应该考虑更好的解决方案吗?下面是我认为EventAggregator可以集成到发布事件的ViewModel中的简化版本。

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));
        }
    }
}

3 个答案:

答案 0 :(得分:3)

你当然可以使用事件聚合器,但你不需要一个像这样简单的东西。您只需让ListViewViewModel听取TreeViewViewModel.PropertyChanged

答案 1 :(得分:2)

EventAggregator是一个不错的选择,你的代码对我来说是正确的。 其他选项可能是SharedService,或者只是从一个视图模型直接引用到另一个视图模型。 Prism框架有关于此主题的很好的文档: http://msdn.microsoft.com/en-us/library/ff921122(v=PandP.40).aspx

答案 2 :(得分:1)

相关问题