views:

99

answers:

1

Hello,

I need to fire command from WP7 applicationbar. Unfortunately it is not possible, but Laurent published interesting workaround:

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

Unfortunately my code behind does not see MainViewModel class or actually any ViewModel class at all! Data binding works well so ViewModel is working fine. What am I doing wrong?

A: 

Put a breakpoint on that line of code and check what the value of DataContext is when the breakpoint is hit. If it's null you've probably forgotten to set the data context in your view.

If the DataContext isn't null, make sure it's of type MainViewModel or else the line calling vm.MyCommand.Execute(null) won't ever be called.

Based on the code you pasted, your view should look something like this.

<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>

This assumes your ViewModelLocator has the property Main of type MainViewModel.

Matt Casto
Actually the problem was much easier. I took a look at some examples and I found out the issue - in your page code behind you need to add a viewmodel namespace! Simple!