2011-02-02 83 views
2

目前正试图从视图模型的构造我的视图模型发送邮件才发现这些邮件永远不会出动。我在做什么是类似以下内容:MVVM光工具包无法发送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; 
      } 
     } 
    } 
} 

究竟是什么,我做错了消息没有从构造函数派发?

干杯

+0

是否在调用Register方法之前发送消息? – 2011-02-15 12:12:39

回答

0

这种方法的问题是,视图模型构造的视图构造函数之前运行,所以在注册前发生的消息被分派。使用MVVMLight的Event-to-Command功能来侦听Window的Loaded事件是适当的。详情请参阅How to fire a Command when a window is loaded in wpf