在該行代碼上放置一個斷點,並檢查命中斷點時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的主要。
其實這個問題要容易得多。我看了一些例子,發現了這個問題 - 在你的頁面代碼中需要添加一個viewmodel命名空間!簡單! – user459497 2010-09-28 18:12:40