C# 使用MVVM轻消息而不是事件
我正在为我当前的WPF项目使用MVVMLight,我想知道什么时候应该在WPF事件上使用MVVMLight的消息传递 WPF事件: MyControl.xaml MVVM轻消息传递: MyControl.cs ListViewSelectionMessage.cs MyViewModelC# 使用MVVM轻消息而不是事件,c#,wpf,xaml,mvvm,mvvm-light,C#,Wpf,Xaml,Mvvm,Mvvm Light,我正在为我当前的WPF项目使用MVVMLight,我想知道什么时候应该在WPF事件上使用MVVMLight的消息传递 WPF事件: MyControl.xaml MVVM轻消息传递: MyControl.cs ListViewSelectionMessage.cs MyViewModel 公共类MyViewModel { MyViewModel() { Messenger.Default.Register(this,this.ListViewSelectionChaged); } 私有无效Lis
公共类MyViewModel
{
MyViewModel()
{
Messenger.Default.Register(this,this.ListViewSelectionChaged);
}
私有无效ListViewSelectionChaged(ListViewSelectionMessage消息)
{
// ...
}
}
因为使用Messanger一切都很容易解耦,所以我很想在任何地方都使用Messanger。使用Messanger而不是Events是否有问题?或者这会产生我不知道的问题。谢谢 一般来说,任何MVVM框架(Prism、MVVM Light)中的消息都是使用插件体系结构的应用程序中松散耦合组件之间通信的好方法,因为您可以通过共享库中声明的契约将消息从一个模块发送到另一个模块。当您单独开发应用程序或在一个小团队中开发高技能程序员时,可以使用它 否则就有一个主要缺点:重构和调试非常困难,因为您不能只单击消息和“查找用法”,您需要首先转到合同(接口),而不是“查找用法”,然后使用Subscribe/Register指令直观地查找位置。此外,开发人员通常会忘记取消订阅消息,所以当从一个模块发送并打算在同一模块中处理的消息被错误地处理到其他模块中时,您将面临问题,因此它将导致意外行为并创建许多痛苦的错误
以上都是基于我个人的经验,所以结果可能会有所不同。只要小心留言,它会很好地为你服务。另外,在我看来,消息作为事件的替代物有点开销/过度工程化,因为当您拥有紧密耦合的组件时,您并不真正需要它。我使用EventToCommand代码而不是events,它允许我根本不编写任何代码(在对话框窗口上调用Close()除外)一般经验法则:ViewModel通信的消息、用户控件的事件或视图特定的内容(所有不能通过“交互行为”完成的事情)
<ListView SelectionChanged="ListView_OnSelectionChanged" />
private MyViewModel ViewModel
{
get { return this.DataContext as MyViewModel; }
}
private void ListView_OnSelectionChanged( object sender, SelectionChangedEventArgs e )
{
this.ViewModel.ListViewSelectionChanged( ( (ListView) sender ).SelectedItems );
}
private void ListView_OnSelectionChanged( object sender, SelectionChangedEventArgs e )
{
Messenger.Default.Send( new ListViewSelectionMessage {SelectedItems = ((ListView)sender).SelectedItems} );
}
public class ListViewSelectionMessage
{
public IList SelectedItems { get; set; }
}
public class MyViewModel
{
MyViewModel()
{
Messenger.Default.Register<ListViewSelectionMessage>(this, this.ListViewSelectionChaged);
}
private void ListViewSelectionChaged( ListViewSelectionMessage message )
{
// ...
}
}