【问题标题】:How can I navigate from an "external" .cs file in Silverlight如何从 Silverlight 中的“外部”.cs 文件导航
【发布时间】:2011-07-21 10:39:36
【问题描述】:

我知道标题不是很清楚,我会尽量解释清楚。

我的 MainPage.xaml 中有一个列表框,我想以某种方式填充它。为此,我有一个没有附加 xaml 的 Home.cs 文件,其构造函数如下:

public Home(string sid, ListBox lb){...}

在这个构造函数中,我使用 Webclient 执行几个 POST 请求,并且在 UploadStringCompleted 方法中,我创建了几个元素、堆栈面板、文本块和一个超链接按钮。

StackPanel bigPanel = new StackPanel();
bigPanel.Width = 456;

HyperlinkButton hyperlink = new HyperlinkButton();
hyperlink.Content = friend.name + " " + person.surname;
hyperlink.Click += new RoutedEventHandler(hyperlink_Click);
bigPanel.Children.Add(hyperlink);

lb.Items.Add(bigPanel);

问题来了。我希望这个超链接导航到另一个页面(FriendPage.xaml),但我无法实现它,因为如果我尝试添加 NavigationService.Navigate(new Uri("/FriendPage.xaml", Urikind.Relative)) 那么它失败,它说“非静态方法 Navigate 需要对象引用”。

据我所知,这行代码应该在 MainPage.xaml 中,那么,有没有办法做到这一点?或者将 hyperlink.Click 事件处理程序放置在 MainPage.xaml.cs 中并将其绑定到尚不存在的超链接按钮?

谢谢

【问题讨论】:

    标签: c# silverlight navigation


    【解决方案1】:

    您不能使用 NavigationService.Navigate 函数,因为 NavigationService 在这里是一个类,而不是一个对象。我认为您必须将 NavigationService 添加到 home 构造函数中的参数中,然后您可以使用它。像这样:

    public void nav(NavigationService ANavigationService)
    {
       ANavigationService.Navigate(new Uri(""));
    }
    

    MainPage 应该有一个 NavigationService 的实例,您可以将其传递给 Home

    编辑: 您可以通过以下方式在 MainPage 中获取导航服务的实例:

    //in mainpage
    NavigationService navService = NavigationService.GetNavigationService(this);
    

    【讨论】:

    • 耶!事实上 NavigationService.GetNavigationService(this) 没有工作,但 this.NavigationService 做到了,所以你的答案是
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 2018-06-17
    相关资源
    最近更新 更多