Thursday 10 June 2010

Windows Phone 7: Binding to ApplicationBar properties

I’ve been playing recently with WP7 development and transitions in particular. In some cases you need to change your ApplicationBar with respect to some ViewModel properties. Edit mode or some NullPattern for bindable list may be good examples for such situations. I wish that thing was easy or obvious (if it is easy but I could not find it :)), but I had to work around this issue with DependencyProperties and manual binding.

Let’s start of a dream:


This is an ideal variant: simple binding and everyone is happy. However, this particular example raises an ‘Invalid XAML’ error. This error makes me think that may be there is a correct way to do what I’m doing but I'’m satisfied for now with my solution.

So what are we going to do? We’re going to do the following:

  1. Detect DataContext change (this is our ViewModel we should update our ApplicationBar according to)
  2. Detect change of property we should bind to and update ApplicationBar respectively

We’re going to use dependency properties for handling necessary changes.

First, let’s handle DataContext changes:


Here we are defining a CustomDataContext property which is bound to DataContext property of our MainPage. We don’t specify binding property because it will default to DataContext – just what we need.

What should we do in our handler? We should start listening to desired changes and handle them. How? Quite the same – using yet another DependencyProperty:


We’ve defined what reaction we expect from ViewModel property change. Now we have to tie it together with some specific property in our data context. This action will take place in the DataContextChanged handler:


So here we bind our ExtraListNotEmpty dependency property to ListIsNotEmpty property of our ViewModel. Moreover, we explicitly call UpdateApplicationVisibility method that updates ApplicationBar visibility according to specific parameters. We have to do this because by default binding won’t ask for value until it changes – but we need this update at the very beginning.

Let’s finally have a look at the code all previous lines were supposed to support:

ListNotEmptyChangeHandler VisibilityUpdater

ListNotEmptyChanged handler is very simple – it calls UpdateApplicationBarVisibility method we’ve already talked about. This method takes current data context and decides whether we should display our application bar or not.

If someone find another way to do this – please tell me. I really want to replace all this code with the single binding line I’ve shown in the very beginning.

No comments: