【问题标题】:Wpf MVVM UI do not update implementing modularity,eventaggregatorWpf MVVM UI 不更新实现模块化,事件聚合器
【发布时间】:2012-04-19 15:54:18
【问题描述】:

我目前正在使用 prism IEventAggregator 在不同模块的两个视图之间试验 wpf 通信。发布模块和订阅模块工作正常,由于某种原因,我不明白为什么订阅者 UI 没有更新。我在订阅者模块上放置了一个按钮来显示一个 msgbox,以确保它接收到它并且它确实接收到它。我认为我正确实施了 INotifyPropertyChanged。

如果我将订阅放在订阅者视图的代码隐藏中,它会按照我想要的方式工作....我做错了吗?请纠正我。谢谢。

用于模块消息传递的单独类。这门课来自这篇文章 http://www.shujaat.net/2010/12/wpf-eventaggregator-in-prism-40-cal.html

Public Class SendServices
Public Shared Property SendMessage As EventAggregator

Shared Sub New()
    SendMessage = New EventAggregator
End Sub
End Class

出版商:

Public Class Module1ViewModel

Private _msgsend As String
Public WriteOnly Property MessageSend As String
    Set(value As String)
        _msgsend = value
    End Set
End Property

Public Sub Send()
    SendServices.SendMessage.GetEvent(Of SendStringEvent).Publish(New SendString With {.Name = _msgsend})
End Sub
End Class

订阅者:

Public Class Module2ViewModel
Implements INotifyPropertyChanged

Private _receivedMSG As String
Public Property ReceivedMSG As String
    Get
        Return _receivedMSG
    End Get
    Set(value As String)
        _receivedMSG = value

        OnPropertyChanged("ReceivedMSG")
    End Set
End Property
'Binded to subscriber View button using interactions
Public Sub Received()
    MsgBox(ReceivedMSG)
End Sub

Private Sub ReceivedMessage(msg As SendString)
    _receivedMSG = msg.Name
End Sub

Public Sub New()
    SendServices.SendMessage.GetEvent(Of SendStringEvent)().Subscribe(AddressOf ReceivedMessage, ThreadOption.UIThread, False)
End Sub

Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Sub OnPropertyChanged(ByVal name As String)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(name))
End Sub
End Class

订阅者查看代码隐藏

Public Class Module2View
    Sub New()
        InitializeComponent()
        Me.DataContext = New Module2ViewModel
    End Sub
End Class

以及显示消息的绑定部分

<TextBox Height="23" HorizontalAlignment="Left" Margin="111,39,0,0" Name="TextBox1" VerticalAlignment="Top" Width="158" Text="{Binding Path=ReceviedMSG}"/>

【问题讨论】:

    标签: wpf mvvm eventaggregator


    【解决方案1】:

    您不会触发 OnPropertyChanged 事件,因为您直接在处理程序中设置字段 _receivedMSG 绕过了触发事件的属性设置器。

    所以你应该改用属性设置器:

    Private Sub ReceivedMessage(msg As SendString)
        ReceivedMSG = msg.Name
    End Sub
    

    【讨论】:

    • 运行时Visual Studio的输出窗口是否有绑定错误?
    • none no error.. 我创建了第二个按钮和标签,这是一个将标签内容绑定到的属性。一个新的子设置第二个属性来保存 ReceivedMSG 并且正如预期的那样,标签内容更改为我想要的输出。由于某种原因,文本框文本不会更新。
    • 试试:Text="{Binding Path=ReceviedMSG, Mode=TwoWay}" 虽然这应该是 wpf 中的默认设置...
    • 如果您在代码隐藏的某处设置TextBox1.Text,它将覆盖绑定。也许您在测试期间在某处留下了处理程序...
    • 已经尝试过设置双向模式,还是没有自动更新。我注释掉了代码隐藏中的所有代码,除了上面的订阅者视图代码隐藏之外..
    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 2021-12-20
    • 2014-11-23
    • 2011-07-24
    • 2016-12-17
    • 2011-04-16
    • 1970-01-01
    相关资源
    最近更新 更多