为什么我们不能在没有任何 PayLoad 的情况下发布事件。
_eventAggregator.GetEvent<SelectFolderEvent>().Publish(new SelectFolderEventCriteria() { });
现在,我不需要在这里传递任何有效载荷。但是 EventAggregator 实现要求我有一个空类来做到这一点。
事件:
public class SelectFolderEvent : CompositePresentationEvent<SelectFolderEventCriteria>
{
}
有效载荷:
public class SelectFolderEventCriteria
{
}
为什么 Prism 没有给出只使用 Event 并像这样发布它的方法
_eventAggregator.GetEvent<SelectFolderEvent>().Publish();
是设计使然,我不明白吗?
请解释。谢谢!
最佳答案
好问题,我没有看到不发布没有有效负载的事件的理由。在某些情况下,已引发事件的事实就是您需要和想要处理的所有信息。
有两种选择: 因为它是开源的,所以您可以使用 Prism 源并提取一个不需要负载的 CompositePresentation 事件。
我不会那样做,而是将 Prism 作为 3rd 方库处理并保持原样。写一个 Facade 是个好习惯让第 3 方库适合您的项目,在本例中为 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);
}
}
如果有什么不清楚的,请追问。
关于mvvm - 在 Prism EventAggregator 中发布没有 PayLoad 的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15430059/