Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP7 -- NavigationService.Navigate is complaining that it is not receiving an object reference . . . but why?

WP7 newb question here.

I have the following code:

public class KeyboardHandler : INotifyPropertyChanged
{
    // lots of methods here

    public void FunctionKeyHandler()
    {
        Uri targetUri = new Uri("/View/SelectTable.xaml",System.UriKind.Relative);
        NavigationService.Navigate(targetUri);
    }
    // more methods

}

I am getting an error:
"Error 1 An object reference is required for the non-static field, method, or property 'System.Windows.Navigation.NavigationService.Navigate(System.Uri)'

Why?

like image 941
William Jockusch Avatar asked May 14 '11 16:05

William Jockusch


2 Answers

NavigationService is the name of a property in the PhoneApplicationPage class, but it is also the name of the class.

When you call the NavigationService.Navigate() method from a page, you use the object from the base class. But in your case, you don't have an object with this name, so the compiler try to access the NavigationService class, and make a call like if Navigate was a static method.

But it is not static, this is why you receive this error : you must use an instance of NavigationService

like image 38
glacasa Avatar answered Oct 13 '22 22:10

glacasa


The Navigate method is actually part of the non-static NavigationService class. Since it's non-static, you need to create an instance of it. The reason you haven't had to create an instance before is because it's part of the Page object, but since you're not inheriting from the Page object, you don't have access to the NavigationService instance.

There are various ways around this such as creating an event handler in your usercontrol that your host Page object (e.g. MainPage) can subscribe to and have it fire the NavigationService on its behalf.

Or you can simply access the NavigationService from the Application host like so:

(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(targetUri);
like image 182
keyboardP Avatar answered Oct 13 '22 20:10

keyboardP