WPF Prism7.0+ IEventAggregator(订阅)
Prism 提供了事件聚合器(Event Aggregator)来实现事件的订阅和发布,允许模块之间进行松耦合的通信。
主要作用:
- 解耦合:通过事件订阅和发布,模块之间可以实现解耦合,避免直接依赖于彼此的实现细节。
示例用法:
- 定义事件类:
public class MessageEvent : PubSubEvent<string> { }
- 订阅事件:
eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageEventReceived);
- 处理事件:
private void OnMessageEventReceived(string message)
{
// 处理接收到的事件
}
- 发布事件:
eventAggregator.GetEvent<MessageEvent>().Publish("Hello, Prism!");
- 解约事件:
eventAggregator.GetEvent<MessageEvent>().Unsubscribe(OnMessageEventReceived);
示例实现如下:示例下载 PrismCore.zip
第一步、创建订阅
public class MessageEvent : PubSubEvent<string> { }
第二步:创建区域接收消息
public partial class EventControl : UserControl { public EventControl(IEventAggregator eventAggregator) { InitializeComponent(); eventAggregator.GetEvent<MessageEvent>().Subscribe(arg => { MessageBox.Show($"接收到消息:{arg}"); }); } }
第三步:MVVM发送消息
public class MainWindowViewModel : BindableBase { private readonly IEventAggregator agregator; private readonly IRegionManager regionManager; public DelegateCommand EventCommand { private set; get; } public MainWindowViewModel(IRegionManager _regionManager, IEventAggregator _eventAggregator) { EventCommand = new DelegateCommand(ExecuteEventCommand); _regionManager.RegisterViewWithRegion("EventRegion", typeof(Regions.EventControl)); regionManager = _regionManager; eventAggregator= _eventAggregator; } private void ExecuteEventCommand() { eventAggregator.GetEvent<MessageEvent>().Publish("Hello, Prism!"); } }
第四步:XAML 代码
<ContentControl Grid.Row="2" prism:RegionManager.RegionName="EventRegion"/> <Button Content="发送订阅消息" Width="120" Margin="50 0"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:InvokeCommandAction Command="{Binding EventCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> </Button>