2010-09-27 46 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