Use the WP8 appbar in ANY MVVM framework

While some frameworks, like Caliburn.Micro,have the possibility the use the appbar button with no code at all in the cod behind file, most frameworks don’t. This blogpost explains how you can use the appbar buttons in any mvvm framework the doesn’t support this feature, like MVVM Light or NRoute.

The solution I found is very simple, some people will say that is not fully MVVM complainant. But in my opinion it is, I will also explain why I believe it is MVVM.

If you used Google to solve this problem, you have probably seen several solution that require a bunch XAML and 1 or more external libraries. I’ve tried they too, they work, but they also make the XAML less readable and increase the size and decrease the speed of your app. And that are real disadvantages.

My simple solutions it to use the code-behind file. In the XAML you put this code:

    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True" Opacity="1">
            <shell:ApplicationBarIconButton x:Name="Cancel" IconUri="/Toolkit.Content/ApplicationBar.Cancel.png" Text="Cancel" Click="Cancel_Click"></shell:ApplicationBarIconButton>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

And in the code behind this (when using a framework that uses a viewmodellocator):

private void Cancel_Click(object sender, System.EventArgs e)
{   
    ViewModelLocator.RapportageStatic.Cancel();
}

Or this, in any other case:

private void Cancel_Click(object sender, System.EventArgs e)
{   
    ((RapportageViewModel)this.DataContext).Cancel();
}

 

I hear you think:”When using MVVM the code behind should be empty” but that is absolutely not true. MVVM is about separation of concerns, and this solution respects that fully. Why? Well the code behind is part of the VIEW, and the only thing it does, is call the appropriate method in the VIEWMODEL. Just like  EventToCommand does in the XAML and the code is still fully automatic testable.

If you think that this breaks MVVM, I disagree, but I still advise you to use this. Any framework should make your work easier, not harder, breaking the rules a little can do no harm.

Comments are closed.