MVVM Light Toolkit无法向ViewModel构造函数发送NotificationMessage

时间:2011-02-02 20:53:21

标签: c# mvvm-light

目前尝试从viewmodel的构造函数发送来自viewmodel的消息,但却发现消息永远不会被分派。我正在做的是类似于以下内容:

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;
            }
        }
    }
}

我错误地认为没有从构造函数中分派消息是什么?

干杯

1 个答案:

答案 0 :(得分:0)

此方法的问题是ViewModel构造函数在View构造函数之前运行,因此在注册发生之前会调度消息。使用MVVMLight的Event-to-Command功能来监听Window的Loaded事件是合适的。有关详细信息,请参阅How to fire a Command when a window is loaded in wpf