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.

3 thoughts on “GoBackAction–a Windows Phone Behavior to navigate back

  1. Denis

    i also added one line of code:

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

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *