WPF - 导航到包含在 Window 中的框架内的不同页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20189888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:07:08  来源:igfitidea点击:

WPF - Navigate to different pages inside a frame which is contained in Window?

wpfnavigationwindowframe

提问by Nikhil Vartak

I have a Main window which contains a frame. Purpose is to display different views (pages) inside a frame.

我有一个包含框架的主窗口。目的是在一个框架内显示不同的视图(页面)。

<Window>
  <Frame Source="Page1.xaml" />
</Window>

Page1.xaml is of type Pageand contains a button, say Button1. On click of Button1 I would like to navigate to Page2.xaml. However the following breaks the application at run time:

Page1.xaml 是Page类型并包含一个按钮,例如 Button1。单击 Button1 时,我想导航到 Page2.xaml。但是,以下内容会在运行时中断应用程序:

private void OnButton1Click(object sender, SelectionChangedEventArgs e)
{
   NavigationService.Content = null; //I tried this thinking exception is caused because Page1.xaml is already present in frame. But no luck! :(
   NavigationService.Navigate(new Uri("Page2.xaml", UriKind.Relative));
}

it throws XamlParseException 'Set property 'System.Windows.FrameworkElement.Style' threw an exception.'Inner Exception reads Specified element is already the logical child of another element. Disconnect it first.

它抛出XamlParseException '设置属性 'System.Windows.FrameworkElement.Style' 抛出异常。内部异常读取指定元素已经是另一个元素的逻辑子元素。先断开它。

I suspect this has got something to do with style resources too because if I keep a blank grid in Page2.xaml navigation works without problems. :-|

我怀疑这也与样式资源有关,因为如果我在 Page2.xaml 中保留一个空白网格,导航工作没有问题。:-|

Edit: Started adding elements with Styles one by one to Page2.xaml and realised that it breaks only when I add a style resource that sets embedded image (image comes from separate dll, Assets) as button content. Style in question is defined as below in a separate Style.xaml file (resource dictionary):

编辑:开始将带有样式的元素一一添加到 Page2.xaml 并意识到只有当我添加将嵌入图像(图像来自单独的 dll,资产)设置为按钮内容的样式资源时它才会中断。有问题的样式在单独的 Style.xaml 文件(资源字典)中定义如下:

<Style x:Key="BackButton" TargetType="Button">
   <Setter Property="Content">
      <Setter.Value>
         <Image Source="/Assets;component/Images/back.png" />
      <Setter.Value>
   </Setter>
</Style>

If I comment the Setter for Content property, navigation works fine. So as a quick solution I added back image as direct content of button on Page2.xaml.

如果我评论 Setter for Content 属性,导航工作正常。所以作为一个快速的解决方案,我在 Page2.xaml 上添加了图像作为按钮的直接内容。

回答by paparazzo

This is from working code
But it does not use NavigationService
It updates the frame directly

这是来自工作代码
但它不使用 NavigationService
它直接更新框架

PageDocFieldDetail pageDocFieldDetail = new PageDocFieldDetail();
framePageDocFieldDetail.Content = pageDocFieldDetail;