我不知道为什么您在 closebt_MouseDown 处理程序中创建另一个 MainWindow 实例,但我希望以下代码对您有所帮助:
private void closebt_MouseDown(object sender, MouseButtonEventArgs e)
{
MainWindow main = Application.Current.MainWindow as MainWindow;
if (main != null)
{
main.Exitbt_PreviewKeyDown(main.Exitbt, e);
main.Close();
}
}
Edited:
我认为您的应用程序的主 Window 对象是MainWindow
,所以我认为前面的代码可以让您的应用程序窗口关闭。
但正如你评论的那样,Application.Current.MainWindow
不同于MainWindow
,以及main
became null
.
因此,我认为获取主 Window 对象的简单方法是在页面类中创建以下构造函数来保留引用:
class YourPageClass
{
public YourPageClass(MainWindow mainWindow)
{
main = mainWindow;
}
private MainWindow main;
(snip)
}
然后,通过传递主 Window 对象创建此实例:
// somewhere in MainWindow code where instantiate your page object
var page = new YourPageClass(this);
通过这样做,您可以获得主 Window 对象。
现在,您可以按如下方式关闭 Window 对象:
// in YourPageClass code
private void closebt_MouseDown(object sender, MouseButtonEventArgs e)
{
if (main != null)
{
main.Exitbt_PreviewKeyDown(main.Exitbt, e);
main.Close();
}
}