views:

287

answers:

5

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

A: 

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.

Enough already
A: 

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

Alan
+1  A: 

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.

Brendan Enrick
well, in the UserControl, I have a button, when it is clicked, I navigate to another page.
Alan
Can you use a HyperlinkButton instead of the regular button?
Brendan Enrick
I would say don't navigate from the control but rather give an event to the page and allow the page to navigate. Your control should only offer input not control navigation.
Bobby Cannon
A: 
        if(Application.Current.RootVisual is Page)
        {
            ((Page) (Application.Current.RootVisual)).NavigationService.Navigate(uri);
        }
Vincent BOUZON
A: 

Sorry for no reputation, otherwise i'd clicked for Vincent's last answer to be useful

MarcelMarnix