我正在使用现代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目标''”。
我缺少什么,以及如何正确导航?
答案 0 :(得分:10)
使用NavigationService
使用导航服务在页面之间导航
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。或者,您可以通过一些辅助函数找到合适的父级。
例如
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";