So I have a window that can be launched by pressing a button. The user can press this multiple times to get different results in that window (refreshing the results). I'm using an anonymous delegate to handle the closing of the window, and to set the view to null so that it can be created again. If I don't do this the window gets disposed but it still hangs around so I cannot call Show() on a window that already exited. Here is my code:
if (ResultsView == null) { ResultsView = new View.ResultsView(); }
//set the data context
ResultsView.DataContext = vm;
//this will close the window properly, so it can be recreated if needed.
EventHandler handler = null;
handler = delegate
{
ResultsView.Closed -= handler;
ResultsView = null;
};
ResultsView.Closed += handler;
//if the view is not loaded show it.
if (!ResultsView.IsLoaded)
{
ResultsView.Owner = Application.Current.MainWindow;
ResultsView.Show();
}
This works fine, except if the results window is open and the user clicks the button again to refresh the resultsview. If this occurs, when the window is closed, the handler is now null for some reason, and I get a null exception trying to unsubscribe from the closed event. When I walk though the code the handler doesn't seem to be null.
You only want to attach a new handler when you create a new window. Have all of the code that declares the handler up until you add the handler included in the body of the if in which you create a new window.
If you don't, you're adding the handler again to an existing window. You don't want to be doing that.
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