Silverlight - How to navigate from a User Control to a normal page?

24,389

Solution 1

(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(uri);

Solution 2

I normally use an EventHandler. Example: in your user control, define something like

public event EventHandler goToThatPage;

that you will call in your control foe example like this:

goToThatPage(this, new EventArgs());

Then in the constructor of your MainPage.xaml.cs (if the user control is contained there) you will define:

uxControlName.goToThatPage+= new EventHandler(ControlGoToThatPage);

and somewhere in your MainPage.xaml.cs you finaly declare the action to be done:

    void ControlGoToThatPage(object sender, EventArgs e)
    {
        this.NavigationService.Navigate(new Uri("/Pages/ThatPage.xaml", UriKind.Relative));
    }

Solution 3

Here is another solution for Silverlight for Windows Phone 8:

public Page Page { get; set; }

this.Loaded += delegate
{
    Page = (Application.Current.RootVisual as Frame).Content as Page;
};

Page.NavigationService.Navigate(new Uri("/Alliance.xaml", UriKind.Relative));

Solution 4

NavigationService is a class. Navigate is a method you can call on instances of that class. It is not a static method you can call from outside an object reference.

Basically you need to get the current NavigationService for the current page. This link http://msdn.microsoft.com/en-us/library/system.windows.navigation.navigationservice.aspx should help.

Solution 5

NavigationService is a property of the page object in Silverlight, which is why you are getting this error. It is not a property of a UserControl in Silverlight.

The following are a few options which will be able to solve the issue you're seeing.

  1. Treat the usercontrol as a control. Give it an event which it will fire when the button is clicked. The page can listen for that event and handle the navigation when it fires.

  2. You can either allow your page access to its parent or pass the NavigationService from the page to the usercontrol.

  3. You can also set this up using messaging, but that would be more complicated.Many MVVM frameworks have messaging features. MVVM Light has it.

Share:
24,389
Alan
Author by

Alan

Updated on November 01, 2020

Comments

  • Alan
    Alan over 3 years

    If I do this inside a User Control:

    NavigationService.Navigate(new Uri("/Alliance.xaml", UriKind.Relative));
    

    it says this error:

    An object reference is required for the non-static field, method, or property 'System.Windows.Navigation.NavigationService.Navigate(System.Uri)'

    Thank you


    Well, I solved passing the normal Page as an argument to the User Control, so I could get the NavigationService.