Saturday, January 25, 2014

Building a cross platform solution for Windows Phone and Windows 8. Part VI: Behaviors for coping with orientation changes

Previous parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning

In the last post we looked at an EventToCommand implementation to easily databind our events to commands, even when we don't have a Command property on a control.

In this post, I will run you through another trick, to ease the development of your views.

One of the behaviors you will probably want in your application is the ability to react to orientation changes. You can easily do this by creating an event handler for the OrientationChanged event in the code behind of your page. You will have to do this in every page you want to be able to react to orientation changes. Resulting in copies of the same piece of code all over the place.

But there is actually a more elegant way of dealing with this, and it is based on behaviors. What you can do is write a specific behavior that does nothing more than attach an event handler to the OrientationChanged event of the associated page. Based on the name of the new orientation, you can now load a specific state of you VisualStateManager.


Of course, in XAML, you now have to create the necessary VisualStateGroups for the specific orientations.


The only thing missing still is a small extra piece of XAML to make use of the OrientationChangedBehavior.


That's it, small and simple little trick. In the next part we'll look at the troubles you can have when your application needs to be tombstoned.

Other parts in this series:

Part 0: Intro
Part I: Quick sharing of code
Part II: The class library approach
Part III: We need a pattern
Part IV: Mocking out the differences
Part V: Event to command
Part VI: Behaviors for coping with orientation changes
Part VII: Tombstoning