System.InvalidOperationException: 'Window must be the root of the tree. Cannot add Window as a child of Visual.'

Waller, Reece (Student) 1 Reputation point
2020-08-04T15:18:09.373+00:00

I'm currently working on a project that needs to navigate between a Window and a Page. I've managed to navigate between a Window to a Page using the following code:

    public void AboutButton_Click(object sender, RoutedEventArgs e)
    {
        About about = new About();
        this.Content = about.Content;

    }

However, when I try to navigate back to my Window using this code:

    public void HomeButton_Click(object sender, RoutedEventArgs e)
    {
        MainWindow home = new MainWindow();
        this.Content = home;


    }

It displays the error that is: System.InvalidOperationException: 'Window must be the root of the tree. Cannot add Window as a child of Visual.' I understand now that you cannot navigate back to a Window using a Page, however is there a workaround to this? Something I can implement without too much redesigning of my entire code? Please let me know if you need anymore information!

Reece

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,667 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. DaisyTian-1203 11,616 Reputation points
    2020-08-05T03:13:07.1+00:00

    I will give you a workarount with a demo:

    MainWindow.xaml

    <Frame x:Name="MyFrame"></Frame>  
    <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="AboutButton_Click"/>  
    

    MainWindow.xaml.cs
    15663-capture.png

    0 comments No comments

  2. JACK MAC 1 Reputation point
    2022-11-28T10:19:46.893+00:00

    Parent win!

    0 comments No comments