Silverlight NavigationService 始终为 null。

3

我看到一些人在使用Silverlight创建模板页面时遇到了问题,ContentControls没有父级Frame的NavigationService(当您尝试使用它时,它总是为null)。还有类似情况,Intellisence中存在NavigationService但始终为null。以下是我解决此问题时想出的一个比较优雅的解决方案。要实现整个网站的导航:

  1. Create a new UserControl (I called mine 'NavFrame') that has a Navigation Frame in it (I called mine 'RootFrame').

  2. Inside this Frame you can set whatever content you like.

  3. Set this UserControl as your RootVisual in App.xaml.cs (i.e. this.RootVisual = new NavFrame();).

  4. To use the NavigationService in any of your pages you can type something like:

    ((NavFrame)App.Current.RootVisual).RootFrame.NavigationService
        .Navigate(new Uri("Your Uri", UriKind.RelativeOrAbsolute));
    

+1:刚刚在寻找一些东西,使我能够在App.Xaml.cs类中使用NavigationService。谢谢。 - Neil Knight
2个回答

1

您可以创建一个操作并将其拖放到要进行导航的控件上,就像这样:

public class NavigateAction : TriggerAction<DependencyObject>
{
    public Uri Uri
    {
        get;
        set;
    }

    protected override void Invoke(object parameter)
    {
        var frame = FindContainingFrame(AssociatedObject);

        if(frame == null)
            throw new InvalidOperationException("Could not find the containing Frame in the visual tree.");

        frame.Navigate(Uri);
    }

    protected static Frame FindContainingFrame(DependencyObject associatedObject)
    {
        var current = associatedObject;

        while(!(current is Frame))
        {
            current = VisualTreeHelper.GetParent(current);

            if(current == null)
                return null;
        }

        return (Frame)current;
    }
}

现在你只需要将它拖动并连接到目标页面即可。顺便说一下,这适用于SL4,我从未在SL3上尝试过。URI的格式可以是"/SilverlightApplication1;component/Page1.xaml",或者使用Frame上的UriMapping。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接