Search code examples
c#wpfxamlwindow

WPF: Change Window's Title on every Page Navigation


I have a WPF application consist of a single window MainWindow.xaml

with title Sample_Window

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

See this image

and three pages:

    Page1.xaml
    Page2.xaml
    Page3.xaml

What my question is that I want to change the title of the MainWindow on every page navigation

for e.g when I land to Page1.xaml title should be Sample_Window-Page1 etc.

I've tried below piece of code in XAML:(didn't work)

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

Also, in CS:(didn't work)

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

I also gone through this question How to give title to WPF pages

But didn't get solution to my problem. The title still remains same as Sample_Window


Solution

  • In the case your Title of Page1 is generated dynamically("Customer Joe Smith Details"), you may have a property on Page1ViewModel called Title. In this case you can simply bind to Frame's Content's DataContext from your MainWindow:

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

    If your Page1 Title is static text (Use Title instead of WindowTitle property), then just bind directly to it from your Main Window:

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