1

使用 Prism4 和 MEF,我创建了一个外壳和两个模块(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();
}
4

2 回答 2

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 中执行相同操作,如果在应用程序中的任何位置引发事件,两者都会收到通知。

于 2013-09-30T16:28:59.073 回答
1

MSDN中有一个QuickStart解决方案,它描述了如何从一个模块发布事件并从另一个模块订阅它。您可以在以下Prism 指南附录中找到事件聚合快速入门

有关EventAggregator如何工作的更多信息,您可以参考以下Prism 指南章节:

问候。

于 2013-09-30T16:45:46.240 回答