How to navigate to other page from a user control in Windows Phone 7

Let us say, you have a scenario to navigate from user control

image

In code behind of the user control very first put below namespace,

clip_image001

Next globally define an event as below,

clip_image002

After this you need to create a method to handle page navigation event as below. This function is taking URI to navigate as input parameter.

clip_image003

Let us say you have a button on user control and you want to navigate on click event of that button then you need to call above function inside the click event of the button like below

clip_image005

Finally code behind of user control should look like below


using System;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace test
{
public partial class MyUserControl : UserControl
{

public event EventHandler EventForPageNavigation;

public MyUserControl()
{
InitializeComponent();
}

public void MethodToNavigateToPage(Uri uri)
{
var e = new NavigationEventArgs(null, uri);
if (EventForPageNavigation != null)
EventForPageNavigation(this, e);
}

private void btnNavigate_Click(object sender, System.Windows.RoutedEventArgs e)
{
MethodToNavigateToPage(new Uri("/ImageUpload.xaml", UriKind.Relative));
}
}
}

Next you need to handle this event of the main page where user control is being used. Let us say you are using user control with the name NavigationUserControl. What I mean while adding user control on the XAML of the main page you gave the name NavigationUserControl

First you will have registered the event in the OnNavigatedTo method or constructor of page as below,


NavigationUserControl.EventForPageNavigation += new EventHandler(NavigationUserControl _NavigateToPageEvent);

Then in navigated event navigate to URI as below,


void NavigationUserControl_NavigateToPageEvent(object sender, EventArgs e)
{
NavigationService.Navigate(((NavigationEventArgs)e).Uri);
}

So in this way you can perform navigation in a user control. I hope this post is useful. Thanks for reading

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

4 responses to “How to navigate to other page from a user control in Windows Phone 7”

  1. […] How to navigate to other page from a user control in Windows Phone 7 (Dhananjay Kumar) […]

  2. […] How to navigate to other page from a user control in Windows Phone 7 […]

  3. EventForPageNavigation is always null for some reason. I copied your code completely but this does not seem to work. Can you pleae help?

  4. EventForPageNavigation is always null for some reason. I copied your code completely but this does not seem to work. Can you please help?

Leave a comment

Create a website or blog at WordPress.com