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?
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.
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.
Assuming the second window is defined as public partial class Window2 : Window
, you can do it by:
Window2 win2 = new Window2();
win2.Show();
Write your code in window1
.
private void Button_Click(object sender, RoutedEventArgs e)
{
window2 win2 = new window2();
win2.Show();
}
You can use this code:
private void OnClickNavigate(object sender, RoutedEventArgs e)
{
NavigatedWindow navigatesWindow = new NavigatedWindow();
navigatesWindow.ShowDialog();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
window2 win2 = new window2();
win2.Show();
}