I have a lot of code looking like that :
MyWindow window = new MyWindow(someParam, callingWindow)
With a MyWindow class containing something like that :
public MyWindow.Processing()
{
` // Do processing
...
callingWindow.RefreshListBox(); // Listbox for example
}
Is there a built-in way to await the closing of the window. I would like to be able to write something like that in the callingWindow's class :
await mywindowInstanceCloseEvent;
RefreshListBoxWhenWindowIsClosed();
I wonder if there is an easy way to "pause" a method (whether it's asynchronous or not) until a specific window is closed.
You can use TaskCompletionSource
and Closed
event for this. Here is a method I use:
private Task ShowPopup<TPopup> (TPopup popup)
where TPopup : Window
{
var task = new TaskCompletionSource<object>();
popup.Owner = Application.Current.MainWindow;
popup.Closed += (s, a) => task.SetResult(null);
popup.Show();
popup.Focus();
return task.Task;
}
You can use it like this:
await ShowPopup(new MyWindow());
You can replace Show
method with ShowDialog
if you want the window to be modal.
If you want to get result from the window, you can modify the code to use TaskCompletionSource<Result>
appropriately.
It depends upon what is your need. If you need to show the window as modal dialog use Window.ShowDialog
. Otherwise you can use Window.Closed
event.
If you want to await it, Here is a good answer from @Athari.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With