Reputation:
I'm new to WPF Environment and I would like to know how can I handle the Window_closed event , I mean how can I check if the window is closed or no from another Window form, I have just written some code:
// Window form 1
for (int k = 0; k <= listgrid.Count - 1; k++)
{
test test = new test(listgrid[0]); // the new form ( Window form 2 )
test.Show();
if (test.IsClosed) // I need to check here if the window form 2 is closed or not
{
Console.WriteLine("OKK Is closed after " + test.IsClosed);
test.Show();
}
}
// Second form
public partial class test : Window
{
public bool test_close;
public test(GridModel gridModel)
{
InitializeComponent();
}
private void Window_Closed(object sender, EventArgs e)
{
// base.Close();
IsClosed = true;
Console.WriteLine( " Ok " +IsClosed);
}
public bool IsClosed { get; private set; }
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
IsClosed = true;
}
Upvotes: 1
Views: 960
Reputation: 1086
You can use Application.Current.Windows.OfType().FirstOrDefault() to get the second window during runtime, then you can check it is open or not.I will show you the detailed steps in my demo:
The code for MainWindow.xaml(as first page):
<StackPanel>
<TextBlock Text="This is the first Window" FontSize="30"></TextBlock>
<Button Content="Open Child Window:" FontSize="15" HorizontalAlignment="Left" VerticalAlignment="Top" Width="287" Height="39" RenderTransformOrigin="0.5,0.5" Click="OpenButton_Click" />
<Button Content="Check child " Width="287" Height="39" Click="Button_Click" VerticalAlignment="Center" HorizontalAlignment="Left"/>
</StackPanel>
The code for ainWindow.xaml.cs:
private void Button_Click(object sender, RoutedEventArgs e)
{
var oldWindow = Application.Current.Windows.OfType<SecondWindow>().FirstOrDefault();
if (oldWindow != null)
{
MessageBox.Show("The Child_Window is open!");
}else
{
MessageBox.Show("The Child_Window is closed");
}
}
private void OpenButton_Click(object sender, RoutedEventArgs e)
{
SecondWindow newWindow = new SecondWindow();
newWindow.Show();
}
The code for SecondWindow.xaml is simpler which only has one line code:
<Grid>
<TextBlock Text="This is second Window!" FontSize="30"></TextBlock>
</Grid>
When you run the project, you can get the below result:
Upvotes: 2
Reputation: 406
The simplest answer would be to perform ShowDialog() instead of Show() as this will block the for loop from continuing until the current window has been closed.
The Microsoft documentation states:
When a Window class is instantiated, it is not visible by default. ShowDialog shows the window, disables all other windows in the application, and returns only when the window is closed. This type of window is known as a modal window.
Upvotes: 0