现代 UI WPF 导航

2024-05-23

我正在使用现代 ui wpf 并尝试从 CheckLogin.xaml 页面导航到 MainWindow.xaml 页面(它们位于解决方案根目录中)。我在 CheckLogin.xaml 中写了这样的内容:

BBCodeBlock bbBlock = new BBCodeBlock();
bbBlock.LinkNavigator.Navigate(new Uri(url, UriKind.Relative), this);

我使用以下 url 值:“/MainWindow.xaml”、“pack://application:/MainWindow.xaml”、

但抛出异常“无法导航到 pack://application:/MainWindow.xaml,找不到 ModernFrame 目标 ''”。

我缺少什么,以及如何正确导航?


使用导航服务

使用导航服务在页面之间导航

    string url = "/Page1.xaml";
    NavigationService nav = NavigationService.GetNavigationService(this);
    nav.Navigate(new System.Uri(url, UriKind.RelativeOrAbsolute));

替代方法

使用 uri

    string url = "/Page1.xaml";
    NavigationWindow nav = this.Parent as NavigationWindow;
    nav.Navigate(new System.Uri(url, UriKind.RelativeOrAbsolute));

使用对象

    NavigationWindow nav = this.Parent as NavigationWindow;
    nav.Navigate(new Page1());

这两种方法也都可以实现导航。上面的示例仅在您从 NavigationWindow 的子级(即本例中的 CheckLogin.xaml)使用它们时才有效。或者,您可以通过一些辅助函数找到合适的父级。

Eg.

    NavigationWindow nav = FindAncestor<NavigationWindow>(this);

    public static T FindAncestor<T>(DependencyObject dependencyObject) where T : DependencyObject
    {
        var parent = VisualTreeHelper.GetParent(dependencyObject);

        if (parent == null) return null;

        var parentT = parent as T;
        return parentT ?? FindAncestor<T>(parent);
    }

使用 LinkNavigator

您可能需要指定框架目标

string url = "/MainWindow.xaml";
BBCodeBlock bbBlock = new BBCodeBlock();
bbBlock.LinkNavigator.Navigate(new Uri(url, UriKind.Relative), this, NavigationHelper.FrameSelf);

可以为框架目标指定以下选项

    //Identifies the current frame.
    public const string FrameSelf = "_self";

    //Identifies the top frame.
    public const string FrameTop = "_top";

    //Identifies the parent of the current frame.
    public const string FrameParent = "_parent";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

现代 UI WPF 导航 的相关文章

随机推荐