使用Prism4和MEF我创建了一个shell和两个模块(M1,M2)。
我确实想在M1中打开一个串口,并使用一个接口,从打开的串口发出一个带有数据的事件,我希望M2得到通知,并从串口接收数据。
更具体地说,我使用MVVM模式,因此我想在M1的ViewModel中打开串口,并在收到数据时通知M2的ViewModel。
不幸的是,我很不确定如何在PRISM工作流程中使用该界面。我很感谢每一个帮助。我真的需要一个这个问题的例子。 我添加了代码只是为了让我的问题清楚。
提前致谢。
模块A.cs
[ModuleExport(typeof(ModuleA), InitializationMode = InitializationMode.OnDemand)]
public class ModuleA : IModule
{
[ImportingConstructor]
public ModuleB(IEventAggregator eventAggregator_)
{
EventAggregator = eventAggregator_;
}
[Import]
public IRegionManager RegionManager { get; set; }
public void Initialize()
{
this.RegionManager.RegisterViewWithRegion("RegionA", typeof(ZeroGrid1));
}
}
模块B.cs
[ModuleExport(typeof(ModuleB), InitializationMode = InitializationMode.OnDemand)]
public class ModuleB : IModule
{
[ImportingConstructor]
public ModuleB(IEventAggregator eventAggregator_)
{
EventAggregator = eventAggregator_;
}
[Import]
public IRegionManager RegionManager { get; set; }
public void Initialize()
{
this.RegionManager.RegisterViewWithRegion("RegionB", typeof(ZeroGrid2));
}
}
ZeroGrid1.xaml.cs(类似于ZeroGrid.xaml.cs)
[Export]
public partial class ZeroGrid1
{
[ImportingConstructor]
public ZeroGrid1(ZeroGridViewModel1 viewModel)
{
InitializeComponent();
this.DataContext = viewModel;
}
}
ModuleAViewModel.cs
[Export]
public class ModuleAViewModel: NotificationObject, IDataReciever
{
// OPEN SERIALPORT
//SEND SOMETHING SERIALPORT
//Maybe I also wanna get notification for datareceived here
}
ModuleBViewModel.cs
[Export]
public class ModuleBViewModel: NotificationObject, IDataReciever
{
//GET NOTIFIED WHEN DATARECEIVED FROM SERIALPORT AND RECEIVED DATA
}
IDataReceiver.cs
interface IDataReciever<TData>
{
event Action<TData> DataRecieved;
//some other methods, such as, for example:
//void Open();
//void Close();
}
答案 0 :(得分:1)
通过导出从Prism的'CompositePresentationEvent'派生的类来定义复合演示事件,其中T是事件“有效载荷”的类型。
[Export]
public class DataReceivedEvent : CompositePresentationEvent<object>
{}
让您的两个ViewModel导入该事件:
[Export]
public class ModuleAViewModel: NotificationObject, IDataReciever
{
private DataReceivedEvent _dataReceivedEvent;
[ImportingConstructor]
public ModuleAViewModel(DataReceivedEvent dataReceivedEvent)
{
_dataReceivedEvent = dataReceivedEvent;
_dataReceivedEvent.Subscribe(OnDataReceived);
}
private void OnDataReceived(object payload)
{
// Handle received data here
}
// This method gets called somewhere withing this class
private void RaiseDataReceived(object payload)
{
_dataReceivedEvent.Publish(payload);
}
}
在ViewModelB中执行相同的操作,如果在应用程序中的任何位置引发事件,则会收到通知。
答案 1 :(得分:1)
MSDN 中提供了 QuickStart 解决方案,该解决方案描述了如何从一个模块发布事件并从另一个模块订阅它。您可以在以下棱镜指南附录中找到事件聚合快速入门:
有关 EventAggregator 的工作原理的详情,请参阅以下棱镜指南一章:
问候。