问题描述
WP7 newb 问题在这里.
WP7 newb question here.
我有以下代码:
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
}
我收到一个错误:
"错误 1 非静态字段、方法或属性需要对象引用 'System.Windows.Navigation.NavigationService.Navigate(System.Uri)'
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)'
为什么?
推荐答案
导航 方法实际上是非静态的一部分 NavigationService 类.由于它是非静态的,因此您需要创建它的一个实例.您之前不必创建实例的原因是因为它是 Page 对象的一部分,但由于您不是从 Page 对象继承的,因此您无权访问 NavigationService 实例.
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.
有多种方法可以解决此问题,例如在您的用户控件中创建一个事件处理程序,您的宿主 Page 对象(例如 MainPage)可以订阅该事件处理程序,并让它代表其触发 NavigationService.
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.
或者您可以简单地从应用程序主机访问 NavigationService,如下所示:
Or you can simply access the NavigationService from the Application host like so:
(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(targetUri);
这篇关于WP7 - NavigationService.Navigate 抱怨它没有收到对象引用...但为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!