使用 Prism4 和 MEF,我创建了一个外壳和两个模块(M1,M2)。
我确实想在 M1 中打开一个串行端口,并通过使用一个接口(interface),以及来自打开的串行端口的数据接收事件,我希望 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();
}
最佳答案
通过导出派生自 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 中执行相同操作,如果在应用程序中的任何位置引发事件,两者都会收到通知。
关于c# - 具有事件的复合 WPF GUI 界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19098741/