天下武功 一脉相承
结合JS理解更容易理解:https://www.cnblogs.com/douyuanjun/p/17465402.html
MainWindow.xaml
<Window x:Class="BlankApp1.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
WindowStartupLocation="CenterScreen"
Title="{Binding Title}" Height="350" Width="525" >
<Grid>
<StackPanel>
<Button FontSize="30" Command="{Binding OpenCommand}" Content="订阅"/>
<Button FontSize="30" Command="{Binding SendCommand}" Content="发布"/>
<TextBlock FontSize="30" Text="{Binding Title}"/>
</StackPanel>
</Grid>
</Window>
ViewModels/MainWindowViewModel
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System.ComponentModel.Design;
using System.Windows;
namespace BlankApp1.ViewModels
{
public class MainWindowViewModel : BindableBase
{
private string _title = "Prism Application";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
/**
private readonly IRegionManager regionManager;
public MainWindowViewModel(IRegionManager regionManager)
{
this.regionManager = regionManager;
regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA));
}
**/
public MainWindowViewModel(IEventAggregator eventAggregator)
{
//订阅
OpenCommand = new DelegateCommand(() =>
{
eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageReceived);
//事件过滤器
/**
eventAggregator.GetEvent<MessageEvent>().Subscribe(OnMessageReceived,ThreadOption.PublisherThread,false,msg =>
{
if (msg.Equals("hello_")) return true;
else
return false;
});
**/
});
//发布
SendCommand = new DelegateCommand(() =>
{
eventAggregator.GetEvent<MessageEvent>().Publish("hello_ok");
});
//取消订阅
UnCommand = new DelegateCommand(() =>
{
eventAggregator.GetEvent<MessageEvent>().Unsubscribe(OnMessageReceived);
});
}
public void OnMessageReceived(string message)
{
Title += message + "\r\n";
}
public DelegateCommand OpenCommand { get; set; }
public DelegateCommand SendCommand { get; set; }
public DelegateCommand UnCommand { get; set; }
}
public class MessageEvent : PubSubEvent<string>
{
}
}
标签:DelegateCommand,regionManager,eventAggregator,Prism,事件,using,WPF,public
From: https://www.cnblogs.com/douyuanjun/p/17788957.html