Ahmed Mohammed
Ahmed Mohammed

Reputation: 305

WPF mainwindow content load from a page

I have one MainWindow and one page I load the page content into the mainwindow by that code

NewPage abt = new NewPage();
this.Content = abt;

but how can I unload the page (reload the mainwindow control and close the page) if I use the same code to load mainwindow content I get a runtime error

Upvotes: 2

Views: 2988

Answers (2)

MajkeloDev
MajkeloDev

Reputation: 1661

I don't think loading page into MainWindow content is a good solution, but if You need it You could probably get current state and save it to some property(or some other thing like xml file) before changing. Like Below:

public partial class MainWindow()
{
    FrameworkElement previousContent; // I believe Content property is of FrameworkElement type
    public MainWindow()
    {
        ...
    }
    ...

    public void ChangeContent()
    {
        previousContent = this.Content; // save state
        NewPage abt = new NewPage();
        this.Content = abt; // set new state
    }

    //And later You can restore this state by:
    public void RestorPreviousContent()
    {
        this.Content = previousContent;
    }

Upvotes: 1

Tyler Jennings
Tyler Jennings

Reputation: 8921

The way I have done this is to have a Frame in the XAML like so:

<Frame Grid.RowSpan="4" Grid.ColumnSpan="3" x:Name="_NavigationFrame" NavigationUIVisibility="Hidden"/>

And then I can set a page and unload a page with this:

_NavigationFrame.Navigate(customPage);
//code to hide main page controls
_NavigationFrame.Navigate(null);
//code to make main page controls visible

Upvotes: 2

Related Questions