Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "await" the closing of another window

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.

like image 997
tobiak777 Avatar asked Nov 30 '22 00:11

tobiak777


2 Answers

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.

like image 146
Athari Avatar answered Dec 15 '22 04:12

Athari


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.

like image 23
Sriram Sakthivel Avatar answered Dec 15 '22 04:12

Sriram Sakthivel