发布没有棱镜EventAggregator有效载荷事件?(Publish an Event with

2019-08-17 15:46发布

为什么我们不能发布活动没有任何有效载荷。

    _eventAggregator.GetEvent<SelectFolderEvent>().Publish(new SelectFolderEventCriteria() { });

现在,我不需要在这里通过的任何有效载荷。 但EventAggregator执行任务我有一个空的类来做到这一点。

事件:

  public class SelectFolderEvent : CompositePresentationEvent<SelectFolderEventCriteria>
  {
  }

有效载荷:

  public class SelectFolderEventCriteria
  {
  }

为什么有棱镜没有给出一个办法只有使用事件并发布它像

    _eventAggregator.GetEvent<SelectFolderEvent>().Publish();

它是由设计,我不明白呢? 请解释。 谢谢!

Answer 1:

好问题,我没有看到没有有效载荷不能发布事件的原因。 在有些情况下,一个事件已经被提出的事实是你需要的,要处理所有信息的情况。

有两种选择:由于它是开源的,你可以把棱镜源,并提取不采取有效载荷的CompositePresentation事件。

我不会做,但处理棱镜作为第三方库,离开它,因为它是。 这是写一个很好的做法门面的第三方库,以适应它到你的项目,在这种情况下CompositePresentationEvent 。 这可能是这个样子:

public class EmptyPresentationEvent : EventBase
{
    /// <summary>
    /// Event which facade is for
    /// </summary>
    private readonly CompositePresentationEvent<object> _innerEvent;

    /// <summary>
    /// Dictionary which maps parameterless actions to wrapped 
    /// actions which take the ignored parameter 
    /// </summary>
    private readonly Dictionary<Action, Action<object>> _subscriberActions;

    public EmptyPresentationEvent()
    {
        _innerEvent = new CompositePresentationEvent<object>();
        _subscriberActions = new Dictionary<Action, Action<object>>();
    }

    public void Publish()
    {
        _innerEvent.Publish(null);
    }

    public void Subscribe(Action action)
    {
        Action<object> wrappedAction = o => action();
        _subscriberActions.Add(action, wrappedAction);
        _innerEvent.Subscribe(wrappedAction);
    }

    public void Unsubscribe(Action action)
    {
        if (!_subscriberActions.ContainsKey(action)) return;
        var wrappedActionToUnsubscribe = _subscriberActions[action];
        _innerEvent.Unsubscribe(wrappedActionToUnsubscribe);
        _subscriberActions.Remove(action);
    }
}

如果有不清楚的地方,请询问。



Answer 2:

只是为了更新情况,因为这个问题被问/回答,因为棱镜6.2的,空的有效载荷现在支持棱镜PubSubEvents。

如果您使用的是旧版本,这个博客显示了如何创建一个“空”的类,它清楚地表明了有效载荷的意图: https://blog.davidpadbury.com/2010/01/01/empty-type-parameters /



文章来源: Publish an Event without PayLoad in Prism EventAggregator?