在以对象作为有效负载的视图模型之间使用 Prism 6 事件聚合器

Using Prism 6 Event Aggregator between view models with an object as the payload

你好,我希望你们中的一位能帮助我一些语法。

所以我正在按照这个示例 https://www.codeproject.com/Tips/591221/Simple-EventAggregator-in-WPF-PRISM 使用 Prism 事件聚合器将消息从一个 ViewModel 发送到另一个。

以下代码在将单个字符串作为有效负载发布时效果很好。

internal class OrderSelectedEvent_SS : PubSubEvent<string>
{
    private static readonly EventAggregator _eventAggregator;
    private static readonly OrderSelectedEvent_SS _event;

    static OrderSelectedEvent_SS()
    {
        _eventAggregator = new EventAggregator();
        _event = _eventAggregator.GetEvent<OrderSelectedEvent_SS>();
    }

    public static OrderSelectedEvent_SS Instance
    {
        get { return _event; }
    }
}

发布者(在 ViewModel1 中):

OrderSelectedEvent_SS.Instance.Publish(_strCurrentOrder);

订阅者(在 ViewModel2 中:

OrderSelectedEvent_SS.Instance.Subscribe(OrderSelectedEventHandler_SS);
private void OrderSelectedEventHandler_SS(string strSelectedOrder)
    {
        CurrentOrder = strSelectedOrder;
    }

我想做的是修改以接受一个对象(一个 class 具有多个字符串)作为有效负载。 这是我目前所拥有的:

internal class OrderSelectedEvent : PubSubEvent<object>
{
    private static readonly EventAggregator _eventAggregator;
    private static readonly OrderSelectedEvent _event;
    static OrderSelectedEvent()
    {
        _eventAggregator = new EventAggregator();
        _event = _eventAggregator.GetEvent<OrderSelectedEvent>();
    }

    public static OrderSelectedEvent Instance
    {
        get { return _event; }
    }

    public class OrderSelectedPayload
    {
        public string SelectedOrder { get; set; }
        public string SelectedE32 { get; set; }
    }
}

发布者(在 ViewModel1 中):

OrderSelectedEvent.OrderSelectedPayload ospl = new OrderSelectedEvent.OrderSelectedPayload();
ospl.SelectedOrder = _strCurrentOrder;
ospl.SelectedE32 = _strCurrentE32JobNumber;
OrderSelectedEvent.Instance.Publish(ospl);

订阅者(在 ViewModel2 中:

OrderSelectedEvent.Instance.Subscribe(OrderSelectedEventHandler); 

我在订阅者这里遇到错误:**错误:无法从 'method group' 转换为 'Action'**** 我似乎无法弄清楚我需要什么要做。

private void OrderSelectedEventHandler(OrderSelectedEvent.OrderSelectedPayload ospl)
{
    CurrentOrder = ospl.SelectedOrder;
    CurrentE32JobNumber = ospl.SelectedE32;
}

提前感谢您提供的任何指导。

您的问题很简单:您正在定义事件以传递 object 作为有效载荷,然后尝试使用特定的 class 作为有效载荷。要解决此问题,请更改

internal class OrderSelectedEvent : PubSubEvent<object>

收件人:

internal class OrderSelectedEvent : PubSubEvent<OrderSelectedPayload>

或者,您可以更改处理程序签名以匹配事件的预期参数:

private void OrderSelectedEventHandler(OrderSelectedEvent.OrderSelectedPayload ospl)

收件人:

private void OrderSelectedEventHandler(object ospl)