MVVM ViewModel之一不接收消息

时间:2016-11-09 23:10:09

标签: wpf mvvm messaging

在一个MainViewModel中,我发送了一条消息:

private void TextBoxKeyDownVMMethod(KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        MessengerInstance.Send<Messages.WebTab.NavigatingToPageArgs>(new NavigatingToPageArgs { UrlForNavigating = "http://stackoverflow.com/questions/11485897/viewmodel-doesnt-receive-message-in-mvvm-light" });
        //GoToPageInSelectedTabVMCommand.Execute((object)null);
        Keyboard.ClearFocus();
    }
} 

在另一个我收到它:

public WebTabItemVievModel()
{       
    MessengerInstance.Register<NotificationMessage<Messages.WebTab.NavigatingToPageArgs>>(this, _MessageHandler_NavigatingToPage);
}

private void _MessageHandler_NavigatingToPage(NotificationMessage<NavigatingToPageArgs> args)
{
    GoToPageCommand.Execute(args.Content.UrlForNavigating);
}

WebTabItemVievModel在MainViewModel的构造函数中创建为ObservableCollection, 此集合是用于选项卡控件的ItemsSource

public MainViewModel()
        {            
            WebTabItems = new ObservableCollection<WebTabItemVievModel>();            
            WebTabItemVievModel tabItem; 
            tabItem = ServiceLocator.Current.GetInstance<WebTabItemVievModel>();
            tabItem.Header = "Empty tab";
            WebTabItems.Add(tabItem);
            tabItem = new WebTabItemVievModel { Header = "Empty tab" };
            WebTabItems.Add(tabItem);
            tabItem = new WebTabItemVievModel { Header = "Empty tab" };
            WebTabItems.Add(tabItem);           
            tabItem = new WebTabItemVievModel() { AddNewTabOnTabHeaderClick =true};
            WebTabItems.Add(tabItem);
}

WebTabItemVievModel有自己的UserControl用于可视化,它通过MainWindow.xaml中的资源定义绑定:

<Window.Resources>
    <DataTemplate DataType="{x:Type vm:WebTabItemVievModel}"  >
        <v:WebTabItemContentViev></v:WebTabItemContentViev>
    </DataTemplate>
</Window.Resources>

定位器在注册时已经有了true参数。它没有改变任何东西:

    SimpleIoc.Default.Register<WebTabItemVievModel>(true);
    SimpleIoc.Default.Register<MainViewModel>(true);

谁知道为什么WebTabItemVievModels不接收消息?

1 个答案:

答案 0 :(得分:0)

注册类型时

NotificationMessage

但发送类型的时候是 Messages.WebTab.NavigatingToPageArgs

使类型相同,它应该工作