简体   繁体   English

匿名代表关闭窗口

[英]Anonymous delegates to close a window

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. 我正在使用匿名委托处理窗口的关闭,并将视图设置为null以便可以再次创建它。 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. 如果我不这样做,窗口会被丢弃,但它仍然会挂起,所以我不能在已经退出的窗口上调用Show() 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. 如果发生这种情况,当窗口关闭时,由于某种原因,处理程序现在为null,并且我尝试取消订阅已关闭的事件时出现null异常。 When I walk though the code the handler doesn't seem to be null . 当我走过代码时,处理程序似乎不是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的正文中的处理程序。

If you don't, you're adding the handler again to an existing window. 如果不这样做,则会将处理程序再次添加到现有窗口。 You don't want to be doing that. 你不想这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM