Silverlight - 如何从用户控件导航到普通页面?

时间:2010-09-16 19:51:40

标签: c# .net silverlight windows-phone-7

如果我在用户控件中执行此操作:

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

它说错误:

非静态字段,方法或属性'System.Windows.Navigation.NavigationService.Navigate(System.Uri)'

需要对象引用

谢谢


好吧,我解决了将普通的页面作为参数传递给用户控件,所以我可以获得NavigationService。

8 个答案:

答案 0 :(得分:50)

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

答案 1 :(得分:12)

我通常使用EventHandler。例: 在您的用户控件中,定义类似

的内容
public event EventHandler goToThatPage;

你将在你的控制对象中调用这样的例子:

goToThatPage(this, new EventArgs());

然后在MainPage.xaml.cs的构造函数中(如果用户控件包含在那里),您将定义:

uxControlName.goToThatPage+= new EventHandler(ControlGoToThatPage);

在您的MainPage.xaml.cs中的某个地方,您最终会声明要执行的操作:

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

答案 2 :(得分:2)

以下是针对Windows Phone 8的Silverlight的另一种解决方案:

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));

答案 3 :(得分:1)

NavigationService是一个类。 Navigate是一种可以在该类的实例上调用的方法。它不是可以从对象引用外部调用的静态方法。

基本上,您需要获取当前页面的当前NavigationService。这个链接http://msdn.microsoft.com/en-us/library/system.windows.navigation.navigationservice.aspx应该会有所帮助。

答案 4 :(得分:1)

NavigationService是Silverlight中页面对象的属性,这就是您收到此错误的原因。它不是Silverlight中UserControl的属性。

以下几个选项可以解决您所看到的问题。

  1. 将usercontrol视为控件。给它一个事件,当点击按钮时它将触发。该页面可以侦听该事件并在触发时处理导航。

  2. 您可以允许您的页面访问其父级,也可以将NavigationService从页面传递给用户控件。

  3. 您也可以使用消息传递来设置它,但这会更复杂。许多MVVM框架都具有消息传递功能。 MVVM Light有它。

答案 5 :(得分:0)

((Frame)(Application.Current.RootVisual as MainPage).FindName("ContentFrame"))
    .Navigate(new Uri("Page Name", UriKind.Relative));

答案 6 :(得分:0)

我知道这是旧的,但我在Silverlight应用程序上的情况也一样。我想做一些类似于迪帕克答案的事情,但我无法弄明白为什么它在我的情况下不起作用。

原来我需要调用刷新,而不是导航;因为我最初认为如果URI与当前页面相同,导航会重新加载页面。原谅我的初学者。

(((Application.Current.RootVisual as MainPage).ContentFrame as Frame).Content as Page).NavigationService.Refresh();

答案 7 :(得分:-1)

        if(Application.Current.RootVisual is Page)
        {
            ((Page) (Application.Current.RootVisual)).NavigationService.Navigate(uri);
        }