Monday, January 31, 2011

MVVM and the WP7 ApplicationBar

Last week, I spend some time trying to find the best way to use the WP7 ApplicationBar in an MVVM style way.  What makes this hard is that in the current version of the Windows Phone 7 Silverlight framework, it is not possible to attach any command on the ApplicationBarMenuItem and ApplicationBarButton controls.

After trying multiple styles, I choose for the most pragmatic solution(with the risk that the MVVM police will come and arrest me). I simply invoke the command in the ViewModel from the codebehind.

In the XAML I register for the Click event:

<shell:ApplicationBarIconButton Text="Refresh" Click="Refresh_Click" IconUri="/Resources/appbar.refresh.png"/>



And in the code behind I invoke the command:



private void Refresh_Click(object sender, EventArgs e)
{
var vm = DataContext as EventsViewModel;
if (vm != null)
{
vm.RefreshCommand.Execute(null);
}
}


I know that it is less elegant than using attached behaviors, but it works fine.

No comments: