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
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.
精彩评论