MVVM Light Toolkit无法向ViewModel构造函数发送NotificationMessage
目前尝试从视图模型的构造函数从我的视图模型发送消息,却发现消息从未被调度。我正在做的事情类似于以下内容:
public class MainViewModel
{
public MainViewModel()
{
PerformActionCommand = new RelayCommand(OnPerformAction);
RefreshTicketsCommand = new RelayCommand(OnRefreshTickets);
Messenger.Default.Send(new NotificationMessage("DisplayCredentials"));
}
}
接收类已正确设置为接收通知,如下所示:
public partial class MainWindow : Window
{
public MainWindow()
{
public MainWindow()
{
InitializeComponent();
Closing += (s, e) => ViewModelLocator.Cleanup();
Messenger.Default.Register<NotificationMessage>(this, NotificationMessageReceived);
}
private void NotificationMessageReceived(NotificationMessage msg)
{
switch (msg.Notification)
{
case "DisplayCredentials":
CredentialsView = new CredentialsView();
var credentialsDlg = CredentialsView.ShowDialog();
break;
}
}
}
}
我到底做错了什么,消息没有从构造函数中分派?
干杯
Currently trying to send messages from my viewmodel from the viewmodel's constructor only to find that the messages never get dispatched. what I am doing is similar to the following:
public class MainViewModel
{
public MainViewModel()
{
PerformActionCommand = new RelayCommand(OnPerformAction);
RefreshTicketsCommand = new RelayCommand(OnRefreshTickets);
Messenger.Default.Send(new NotificationMessage("DisplayCredentials"));
}
}
The receiving class is correctly set to receive notification and is as follows:
public partial class MainWindow : Window
{
public MainWindow()
{
public MainWindow()
{
InitializeComponent();
Closing += (s, e) => ViewModelLocator.Cleanup();
Messenger.Default.Register<NotificationMessage>(this, NotificationMessageReceived);
}
private void NotificationMessageReceived(NotificationMessage msg)
{
switch (msg.Notification)
{
case "DisplayCredentials":
CredentialsView = new CredentialsView();
var credentialsDlg = CredentialsView.ShowDialog();
break;
}
}
}
}
What is it exactly that I've done wrong that the Messages are not being dispatched from the constructor?
Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这种方法的问题是 ViewModel 构造函数在 View 构造函数之前运行,因此消息在注册发生之前被调度。使用 MVVMLight 的 Event-to-Command 功能来监听 Window 的 Loaded 事件是合适的。请参阅如何在以下情况下触发命令wpf 中加载一个窗口以获取详细信息。
The problem with this approach is that the ViewModel Constructor runs before the View Constructor, so the message gets dispatched before the registration occurs. It would be appropriate to use MVVMLight's Event-to-Command feature to listen to the Window's Loaded event. Please see How to fire a Command when a window is loaded in wpf for details.