Damian Mehers' Blog Android, VR and Wearables from Geneva, Switzerland.

11Apr/113

GoBackAction–a Windows Phone Behavior to navigate back

Behaviors are a great way to encapsulate functionality that can be used in a drag-and-drop environment such as Expression Blend.

Out of the box you get a NavigateToPageAction, but I couldn’t see an easy way to navigate backwards to the previous page using any of the built-in behaviors.  I wanted to let the user click on an item in a list, and then have the Phone automatically navigate to the previous page.

So here it is, the world’s simplest behavior:

[DefaultTrigger(typeof (ButtonBase), typeof (System.Windows.Interactivity.EventTrigger), "Click")]
[DefaultTrigger(typeof (UIElement), typeof (System.Windows.Interactivity.EventTrigger), "MouseLeftButtonDown")]
public class GoBackAction : TriggerAction<FrameworkElement>
{
    protected override void Invoke(object parameter)
    {
        var rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;
        if(rootFrame !=null)
        {
            rootFrame.GoBack();
        }
    }
}

Once you’ve built this class in your project, if you open your project in Expression Blend you should see the GoBackAction listed in the Behaviors section of the Assets tab.  You can then drag the behavior onto a UI element, define the event that should trigger the action, and then when the event occurs you should be automatically navigated backwards.

Filed under: WP7 Leave a comment
Comments (3) Trackbacks (0)
  1. Thanks a lot, Damian! I’ve spent about hour looking for this solution all over the internet…

  2. Thanks a lot! Made my life easier. Also changed my thoughts about behaviors. I’ll use them much more now.

  3. i also added one line of code:

    [DefaultTrigger(typeof(UIElement), typeof(System.Windows.Interactivity.EventTrigger), “Tap”)]


Leave a comment

No trackbacks yet.