How do I open a second window from the first window in WPF?

前端 未结 9 1200
一个人的身影
一个人的身影 2020-11-29 20:46

I am new to WPF. I have two windows, such as window1 and window2. I have one button in window1. If I click that button, the window2 has to open. What should I do for that?

相关标签:
9条回答
  • 2020-11-29 21:06

    In WPF we have a couple of options by using the Show() and ShowDialog() methods.

    Well, if you want to close the opened window when a new window gets open then you can use the Show() method:

    Window1 win1 = new Window1();
    win1.Show();
    win1.Close();
    

    ShowDialog() also opens a window, but in this case you can not close your previously opened window.

    0 讨论(0)
  • 2020-11-29 21:09

    You will need to create an instance of a new window like so.

    var window2 = new Window2();
    

    Once you have the instance you can use the Show() or ShowDialog() method depending on what you want to do.

    window2.Show();
    

    or

    var result = window2.ShowDialog();
    

    ShowDialog() will return a Nullable<bool> if you need that.

    0 讨论(0)
  • 2020-11-29 21:10

    Assuming the second window is defined as public partial class Window2 : Window, you can do it by:

    Window2 win2 = new Window2();
    win2.Show();
    
    0 讨论(0)
  • 2020-11-29 21:17

    Write your code in window1.

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        window2 win2 = new window2();
        win2.Show();
    }
    
    0 讨论(0)
  • 2020-11-29 21:17

    You can use this code:

    private void OnClickNavigate(object sender, RoutedEventArgs e)
    {
        NavigatedWindow navigatesWindow = new NavigatedWindow();
        navigatesWindow.ShowDialog();
    }
    
    0 讨论(0)
  • 2020-11-29 21:18
    private void button1_Click(object sender, RoutedEventArgs e)
    {
        window2 win2 = new window2();
        win2.Show();
    }
    
    0 讨论(0)
提交回复
热议问题