简体   繁体   English

WP7 - NavigationService.Navigate抱怨它没有收到对象引用。 。 。 但为什么?

[英]WP7 — NavigationService.Navigate is complaining that it is not receiving an object reference . . . but why?

WP7 newb question here. WP7新问题在这里。

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)' “错误1非静态字段,方法或属性'System.Windows.Navigation.NavigationService.Navigate(System.Uri)'需要对象引用

Why? 为什么?

The Navigate method is actually part of the non-static NavigationService class. Navigate方法实际上是非静态NavigationService类的一部分。 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. 您之前不必创建实例的原因是因为它是Page对象的一部分,但由于您不是从Page对象继承,因此您无权访问NavigationService实例。

There are various ways around this such as creating an event handler in your usercontrol that your host Page object (eg MainPage) can subscribe to and have it fire the NavigationService on its behalf. 有很多方法可以解决这个问题,例如在你的usercontrol中创建一个事件处理程序,你的主机页面对象(例如MainPage)可以订阅它并让它代表它激活NavigationService。

Or you can simply access the NavigationService from the Application host like so: 或者您只需从Application主机访问NavigationService,如下所示:

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

NavigationService is the name of a property in the PhoneApplicationPage class, but it is also the name of the class. NavigationServicePhoneApplicationPage类中的属性的名称,但它也是类的名称。

When you call the NavigationService.Navigate() method from a page, you use the object from the base class. 从页面调用NavigationService.Navigate()方法时,可以使用基类中的对象。 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. 但在您的情况下,您没有具有此名称的对象,因此编译器尝试访问NavigationService类,并进行调用,就像Navigate是静态方法一样。

But it is not static, this is why you receive this error : you must use an instance of NavigationService 但它不是静态的,这就是您收到此错误的原因:您必须使用NavigationService的实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM