简体   繁体   中英

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

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

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM