简体   繁体   中英

Navigation between Pages and Windows in WPF

I have an issue that I am trying to resolve. I have two WPF windows. Those windows house the pages with content. My problem is not navigating page to page but rather window to window. here is an example of the code:

LoginPortal Design

 <Grid>
    <Frame x:Name="MainFrame" NavigationUIVisibility="Hidden"/>
</Grid>

LoginPortal Code

 public LoginPortalMain()
    {
        InitializeComponent();

        MainFrame.Navigate(new Uri("/Pages/LoginPortal.xaml", UriKind.RelativeOrAbsolute));

     
    }

This is my Login portal that houses 4 buttons. Each button opens the second window which is houses several pages.

private void BtnSales_Click(object sender, RoutedEventArgs e)
    {
        var w = Application.Current.Windows[0];
        w.Hide();
        MainWindow mn = new MainWindow();
        mn.Content = new SalesPage();
        mn.Show();
    }

When this button is clicked it opens the second WPF Window which is where several pages are housed. There is no problem with navigation. The problem starts when I wire the Closing event from the MainWindow to go back to the LoginPortalMain

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        LoginPortalMain lgm = Application.Current.MainWindow as LoginPortalMain;
        lgm.Show();
    }

It then goes back to the start again. Now my problem is if I click on the same button again. It just duplicates everything. Then on closing anything it just adds new windows. My question is, is there a way to either dispose of the navigation once the MainWindow is closed. So there is no duplicate windows once you close the mainWindow a second time. I have used navigation before on a single window but not on multiple windows.

I may have to rethink this whole structure and use custom UserControls and figure out the animation sequence from Pages to UserControls. However, any help would be greatly appreciated.

If you only want to be able to open one instance of the child window try showing and hiding a single window instance.

When the open window button is pressed create the window if need and show it.

private ChildWindow mChildWindow;
private void OpenWindowButtonClick(object sender, RoutedEventArgs e)
{
    mChildWindow ??= new ChildWindow(); //initialize child window on first call
    mChildWindow.Show();
}

When the child window is closed hide it and cancel the close request. You could also reset the child window state here for the next time it is shown.

private void ChildWindowClosingEvent(object sender, System.ComponentModel.CancelEventArgs e)
{
    ((Window)sender).Hide();
    Application.Current.MainWindow.Activate();
    e.Cancel = true;
}

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