这是事件聚合的正确用法吗?

时间:2015-09-22 09:22:51

标签: c# mvvm observablecollection caliburn.micro eventaggregator

亲爱的Stackoverflow用户,

我目前正在开发一个将MVVM模式与Caliburn micro一起使用的应用程序。

我遇到了第一种情况,我需要打开一个对话框,对需要在主视图模型上显示的ObservableCollection进行一些修改。

我第一次发现了事件聚合,并认为它符合我的情况。然而,我不太确定事件聚合是否是最佳解决方案,或者我是否正确使用...因此我的问题。

请记住,名称空间是故意留在那里,因为我弄错了。

设置如下:

namespace Company.Product.Presentation.Core.Events
{
    public class PersonCollectionChanged
    {
        [CanBeNull]
        public ObservableCollection<Person> PersonCollection { get; set; }

        public PersonCollectionChanged(ObservableCollection<Person> personCollection)
        {
            PersonCollection = personCollection;
        }
    }
}

对话框的ViewModel

 namespace Company.Product.Presentation.Modules.Selection
{
    public class SelectionViewModel : Screen
    {
        private readonly IViewModelLoader _viewModelLoader;
        private readonly IEventAggregator _eventAggregator;

        private readonly ObservableCollection<Person> _tempPersonCollection; 

        private readonly PersonCollectionChanged _personCollectionChanged;

        public SelectionViewModel(IViewModelLoader viewModelLoader, 
            IEventAggregator eventAggregator, 
            PersonCollectionChanged personCollectionChanged, 
            ObservableCollection<Person> tempPersonCollection)
        {
            _viewModelLoader = viewModelLoader;
            _eventAggregator = eventAggregator;
            _personCollectionChanged = personCollectionChanged;
            _tempPersonCollection = tempPersonCollection;

            AddPerson(new Person{Name = "Zatixiz"});

            _personCollectionChanged.PersonCollection = _tempPersonCollection;

            _eventAggregator.PublishOnUIThread(_personCollectionChanged);
        }

        internal void AddPerson(Person person)
        {
            _tempPersonCollection.Add(person);
        }
    }
}

订阅活动的主视图模型:

namespace Company.Product.Presentation.Modules.Main
{
    public class MainViewModel : BaseViewModel, IHandle<PersonCollectionChanged>
    {

        private ObservableCollection<Person> _mainPersonCollection;

        public MainViewModel(
            IViewModelLoader viewModelLoader,
            IEventAggregator eventAggregator,
            ObservableCollection<Person> mainPersonCollection) : base(viewModelLoader)
        {
            _mainPersonCOllection = mainPersonCollection;

            eventAggregator.Subscribe(this);

        }

        public void Handle(PersonCollectionChanged message)
        {
            _mainPersonCollection = message;
        }
    }
}

0 个答案:

没有答案