There are too many pages in my project and I want to write the opening and closing of these pages in one class. But it does not open to a new page.
Thank you.
My Class Code
class Class
{
public static void GoToOpenPage1()
{
Frame OpenPage1 = new Frame();
OpenPage1.Navigate(typeof(MainPage));
}
}
Button Click Code
private void button_Click(object sender, RoutedEventArgs e)
{
Class.GoToOpenPage1();
}
After you create a Frame
, it needs to be inserted into the current visual tree so that it can be "see".
For example, we create a Grid in MainPage.xaml
.
<Grid x:Name="FrameContainer" x:FieldModifier="public">
</Grid>
In MainPage.xaml.cs
, we can expose the MainPage instance through static variables.
public static MainPage Current;
public MainPage()
{
this.InitializeComponent();
Current = this;
}
In this way, when MainPage
is loaded, FrameContainer
will also be loaded. We can get this Grid
externally through MainPage.Current.FrameContainer
, and then insert the Frame
we generated into this Grid
, which completes the insertion into the visual tree step.
public static void GoToOpenPage1()
{
Frame OpenPage1 = new Frame();
OpenPage1.Navigate(typeof(OtherPage));
MainPage.Current.FrameContainer.Children.Clear();
MainPage.Current.FrameContainer.Children.Add(OpenPage1);
}
But judging from the code you provided, you seem to be navigating to MainPage
. If you need to make MainPage
become the content of the Window again, you can write like this:
var rootFrame = Window.Current.Content as Frame;
rootFrame.Navigate(typeof(MainPage));
The above content belongs to page navigation, if you want to open a new window, you can refer to this document, which provides detailed instructions: