【问题标题】:Using EventAggregator to communicate between WPF in ElementHost and host WinForm使用 EventAggregator 在 ElementHost 中的 WPF 和宿主 WinForm 之间进行通信
【发布时间】:2012-03-28 14:59:08
【问题描述】:

我可以使用EventAggregator 订阅从 ViewModel 发布的 WinForm 中的事件吗?

我需要将 WPF 复合应用程序的一个模块中在 ElementHost 中托管 WPF 复合应用程序的 WinForm 的属性更改为described here

我认为要解决这个问题,我可以使用 EventAggregator 在 ViewModel 中发布事件,这些事件将由 WinForm 订阅。此事件的参数可能包括我想在 WinForm 上更改的内容,例如标题。

我已阅读以下内容:

http://msdn.microsoft.com/en-us/library/ff921173%28v=PandP.40%29.aspx

http://www.codeproject.com/Articles/355473/Prism-EventAggregator-Sample

http://msdn.microsoft.com/en-us/library/ff649187.aspx

但我仍然无法确定 EventAggregator 是否适合这种情况。

【问题讨论】:

  • 是的,我使用消息总线在同一应用程序中的 MVVM WPF UI 和 WinForms MVP UI 之间进行通信。 WinForms 部分是第三方图表控件。
  • 感谢您的评论。您是否碰巧可以发布任何代码来演示这种通信?我的 ViewModel 没有与 WinForm 耦合。我正在尝试确定如何最好地从 ViewModel 更改该 WinForm 的属性,而无需创建其他依赖项。我希望 Prism EventAggregator 可以让我通过事件来做到这一点,但我现在很难理解如何使用它。
  • 我不喜欢棱镜。查看 MVVM light 的版本。我没有太多可以分享的代码(企业客户),但如果您可以分享您的存储库,我很乐意向您发送一个简单的变更集。

标签: c# wpf winforms


【解决方案1】:

如果所有这些组件都在同一个进程中,那么可以,您可以使用EventAggregator

请记住,您必须在发布者和订阅者中引用相同的聚合器实例 - 聚合器应该是单例或作为单例放入 IoC 容器中。

【讨论】:

    【解决方案2】:

    我确实最终使用了 EventAggregator。这是 VB.NET 中的代码,因为这是我用于这个特定项目的代码。

    1. EventAggregatorSingleton

    Imports System.Threading
    Imports System.Runtime.InteropServices
    Imports Microsoft.Practices.Composite.Events
    
    Public Class EventAggregatorSingleton
    
    Private Shared _currentEventAggregator As EventAggregator
    Private Shared _syncLock As Object = New Object()
    
    Public Shared ReadOnly Property CurrentEventAggregator As EventAggregator
        Get
            If _currentEventAggregator Is Nothing Then
                SyncLock _syncLock
                    If _currentEventAggregator Is Nothing Then
                        Dim currEventAggregator As New EventAggregator
                        _currentEventAggregator = currEventAggregator
                    End If
                End SyncLock
            End If
            Return _currentEventAggregator
        End Get
    End Property
    
    End Class
    

    2。事件类

    Public Class ChartWizardPageChangedEvent
    Inherits CompositePresentationEvent(Of WpfHostForm)
    
    End Class
    

    3。从 ViewModel 发布事件

    EventAggregatorSingleton.CurrentEventAggregator.GetEvent(Of ChartWizardPageChangedEvent)().Publish(_chartWizard)
    

    4.从 WinForm 订阅事件

    EventAggregatorSingleton.CurrentEventAggregator.GetEvent(Of ChartWizardPageChangedEvent)().Subscribe(New Action(Of WpfHostForm)(AddressOf App_HostFormChanged))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多