2010-09-27 47 views
2

我需要从WP7应用程序栏触发命令。不幸的是这是不可能的,但洛朗发表有趣的解决方法:MVVM Light - 如何从代码后面触发命令

private void ApplicationBarMenuItemClick(object sender, System.EventArgs e) 
{ 
    var vm = DataContext as MainViewModel; 
    if (vm != null) 
    vm.MyCommand.Execute(null); 
} 

不幸的是我的代码背后没有看到MainViewModel类或实际上任何ViewModel类了!数据绑定工作正常,所以ViewModel工作正常。我究竟做错了什么?

回答

0

在该行代码上放置一个断点,并检查命中断点时DataContext的值。如果它为空,则可能忘记在视图中设置数据上下文。

如果DataContext不为空,请确保它是MainViewModel类型,否则调用vm.MyCommand.Execute(null)的行将不会被调用。

根据您粘贴的代码,您的视图应该看起来像这样。

<phone:PhoneApplicationPage x:Class="MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" 
    shell:SystemTray.IsVisible="True" 
    DataContext="{Binding Path=Main, Source={StaticResource Locator}}" 
    > 

    <Grid x:Name="LayoutRoot" Background="Transparent"> 
     <!-- the rest has been ommitted for simplicity --> 
    </Grid> 

    <phone:PhoneApplicationPage.ApplicationBar> 
     <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True"> 
      <shell:ApplicationBar.MenuItems> 
       <shell:ApplicationBarMenuItem x:Name="appBarMenuItem1" Click="ApplicationBarMenuItemClick" Text="Menu Item 1" /> 
      </shell:ApplicationBar.MenuItems> 
     </shell:ApplicationBar> 
    </phone:PhoneApplicationPage.ApplicationBar> 
</phone:PhoneApplicationPage> 

这里假设你的ViewModelLocator拥有财产型MainViewModel主要

+0

其实这个问题要容易得多。我看了一些例子,发现了这个问题 - 在你的页面代码中需要添加一个viewmodel命名空间!简单! – user459497 2010-09-28 18:12:40