Fork me on Github

Prism_订阅

1.创建消息事件类,继承发布订阅事件类 PubSubEvent

 /// <summary>
 /// 发布订阅 消息事件类
 /// </summary>
 public class MsgEvent : PubSubEvent<string>
 {

 }

2.获取事件聚合器 IEventAggregator,通过 IEventAggregator 获取消息事件进行发布、订阅和取消订阅

/// <summary>
/// 事件聚合器
/// </summary>
private readonly IEventAggregator EventAggregator;

public MainWindow(IEventAggregator eventAggregator)
{
    InitializeComponent();
    EventAggregator = eventAggregator;
    Action<string> ShowAction = (s) =>
    {
        MessageBox.Show(s);
    };

    /// <summary>
    /// 发布订阅
    /// </summary>
    PubBtn.Click += (s, e) =>
    {
        EventAggregator.GetEvent<MsgEvent>().Publish("好消息!好消息!");
    };

    /// <summary>
    /// 订阅
    /// </summary>
    SubBtn.Click += (s, e) =>
    {
        EventAggregator.GetEvent<MsgEvent>().Subscribe(ShowAction);
    };

    /// <summary>
    /// 取消订阅
    /// </summary>///
    UnSubBtn.Click += (s, e) =>
    {
        EventAggregator.GetEvent<MsgEvent>().Unsubscribe(ShowAction);
    };
}

 

posted @ 2025-05-14 22:12  昂昂呀  阅读(32)  评论(0)    收藏  举报