return to previous window on WPF

后端 未结 2 990
一向
一向 2021-01-15 03:15

I\'m new to WPF and couldn\'t find an answer to to this issue:

I have 3 windows I want to navigate between- MainWindow -> Window1 -> Window2

相关标签:
2条回答
  • 2021-01-15 03:59

    Change the way you show your windows like this:

    private void Window1_Click(object sender, RoutedEventArgs e)
    {
        Hide();
        new Window1().ShowDialog();
        ShowDialog();
    }
    

    And use the DialogResult property to hide your windows (except the main window):

    private void btn_Cancel_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
    }
    
    0 讨论(0)
  • 2021-01-15 04:02

    Here is an example of a navigation service class that holds a stack of navigated windows.

    public static class NavigationService
    {
        static NavigationService()
        {
            NavigationStack.Push(Application.Current.MainWindow);
        } 
    
        private static readonly Stack<Window> NavigationStack = new Stack<Window>();
    
        public static void NavigateTo(Window win)
        {
            if(NavigationStack.Count > 0)
                NavigationStack.Peek().Hide();
    
            NavigationStack.Push(win);
            win.Show();
        }
    
        public static bool NavigateBack()
        {
            if (NavigationStack.Count <= 1)
                return false;
    
            NavigationStack.Pop().Hide();
            NavigationStack.Peek().Show();
            return true;
        }
    
        public static bool CanNavigateBack()
        {
            return NavigationStack.Count > 1;
        }
    }
    

    You can use it from your views' code behind :

        public void OnNextClicked(object sender, EventArgs args)
        {
            NavigationService.NavigateTo(new Window2());
        }
    
        public void OnPreviousClicked(object sender, EventArgs args)
        {
            NavigationService.NavigateBack();
        }
    

    The static constructor adds the main view started from your App.xaml StartupUri to the navigation stack as the initial view.

    If your application has a growing complexity you may also have a look at tools such as prism navigation system.

    0 讨论(0)
提交回复
热议问题