试图了解Caliburn Micro EventAggregator

时间:2017-08-08 22:05:47

标签: c# wpf mvvm caliburn.micro eventaggregator

我了解EventAggregator如何在Caliburn Micro中工作,但我不明白这一点:

我们以此为例:

ViewModel A

private IEventAggregator _eventAggregator;
public ViewModelA(IEventAggregator eventAggregator)
{
   _eventAggregator = eventAggregator
   _eventAggregator.PublishOnUIThread("Hello");
}

ViewModel B

private IEventAggregator _eventAggregator;
public ViewModelA(IEventAggregator eventAggregator)
{
   _eventAggregator = eventAggregator
   _eventAggregator.Subscribe(this)
}
public void Handle(string message)
{ 
   MessageBox.Show(message + " From ViewModel B")
}

ViewModel C

private IEventAggregator _eventAggregator;
public ViewModelA(IEventAggregator eventAggregator)
{
   _eventAggregator = eventAggregator
   _eventAggregator.Subscribe(this)
}
public void Handle(string message)
{ 
   MessageBox.Show(message + " From ViewModel C")
}

那么我如何选择在发布事件时使用哪个viewmodel句柄?

2 个答案:

答案 0 :(得分:1)

  

那么我如何选择在发布事件时使用哪个viewmodel句柄?

多个视图模型可以订阅相同的消息。这是事件聚合的工作方式。发布者在不知道接收者数量的情况下发布单个消息。

如果您希望特定视图模型能够订阅某个事件,它应该实现IHandle<T> intertface并在事件聚合器上调用Subscribe方法:

public class ViewModelA : IHandle<string>
{
    private readonly IEventAggregator _eventAggregator;

    public ViewModelA(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;
        _eventAggregator.Subscribe(this);
    }

    public void Handle(string message)
    {
        MessageBox.Show(message);
    }
}

执行此操作的所有视图模型都将收到消息。

答案 1 :(得分:0)

我设法通过Message类将消息发送到特定的视图模型:

public class Message<TTarget, TValue>
{
    public TValue Value { get; set; }

    public Message(TValue value)
    {
        Value = value;
    }
}

然后添加到课程

IHandle<Message<ViewModel, string>>

用法:

_eventAggregator.PublishOnUIThread(new Message<ViewModel, string>("Hello from ViewModel"));