【问题标题】:Silverlight NavigationService Is Always NullSilverlight NavigationService 始终为空
【发布时间】:2010-04-26 09:07:48
【问题描述】:

我读到有几个人对此有疑问,所以我想发布一个(有点)优雅的解决方案,我在尝试处理这个问题时想出了。问题是当您在 Silverlight 中创建模板页面并且 ContentControls 没有父 Frame 的 NavigationService 时(当您尝试使用它时它始终为空)。在智能中存在 NavigationService 但始终为空的类似场景。要启用站点范围的导航:

  1. 创建一个新的UserControl(我称之为“NavFrame”),其中包含一个导航框架(我称之为“RootFrame”)。

  2. 在此框架内,您可以设置任何您喜欢的内容。

  3. 将此 UserControl 设置为 App.xaml.cs 中的 RootVisual(即 this.RootVisual = new NavFrame();)。

  4. 要在您的任何页面中使用 NavigationService,您可以输入以下内容:

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

【问题讨论】:

  • +1:一直在寻找能够让我在 App.Xaml.cs 类中使用 NavigationService 的东西。谢谢。

标签: silverlight xaml navigation


【解决方案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”或在框架上使用 UriMapping。

【讨论】:

    【解决方案2】:
    ((Frame)(Application.Current.RootVisual as MainPage).FindName("ContentFrame"))
        .Navigate(new Uri("Page Name", UriKind.Relative));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 2019-07-18
      相关资源
      最近更新 更多