WPF:在每个页面导航上更改 Window 的标题

WPF: Change Window's Title on every Page Navigation

我有一个 WPF application 由一个 window MainWindow.xaml

标题为Sample_Window

<Window
   Title="Sample_Window">
<Grid>
   <Frame x:Name="mainFrame" Source="/Page1.xaml" />
<Grid>
</Window>

和三页:

    Page1.xaml
    Page2.xaml
    Page3.xaml

我的问题是我想在每个 页面导航

上更改 MainWindow 的标题

例如,当我登陆 Page1.xaml 时,标题应该是 Sample_Window-Page1

我在 XAML 中尝试了下面的一段代码:(没用)

<Page 
    WindowTitle="Sample_Window-Page1"
    Title="Page1">
</Page>

另外,在 CS 中:(没用)

Page1 mypage= new Page1();
mypage.WindowTitle="Sample_Window-Page1";

我也经历过这个问题How to give title to WPF pages

但是没有解决我的问题。标题仍然与 Sample_Window

相同
this.Title = "Sample_Window-Page1";

你能试试这个吗?框架不会更改 window,因此标题会保留,您应该在每次更改页面时更新 window 的标题。

如果您的 Page1 标题是动态生成的 ("Customer Joe Smith Details"),您可能在 Page1ViewModel 上有一个名为 Title 的 属性。在这种情况下,您可以简单地从 MainWindow:

绑定到 Frame 的 Content 的 DataContext
<Window 
  Title="{Binding ElementName=mainFrame, Path=Content.DataContext.Title}">
  <Grid>
    <Frame x:Name="mainFrame" Source="/Page1.xaml" />
  </Grid>
</Window>

如果您的第 1 页标题是静态文本(使用标题而不是 Window 标题 属性),则直接从您的 Main Window:

绑定到它
<Window 
  Title="{Binding ElementName=mainFrame, Path=Content.Title}">
  <Grid>
    <Frame x:Name="mainFrame" Source="/Page1.xaml" />
  </Grid>
</Window>

以上对我不起作用,因为它在 运行 应用程序时加载了 [myPage1]。我通过单击 MainWindow 上的按钮显示 [myPage1],以便显示带有静态标题的页面,我将所需的标题文本添加到导航中。

MainWindow.xaml

<DockPanel> <Frame x:Name="_mainFrame"/> </DockPanel>

MainWindow.xaml.cs中的button_click方法

_mainFrame.NavigationService.Navigate(new [myPage1] (Title= "what ever you want displayed"));