为什么MainWindow_Closing事件不起作用? [英] Why MainWindow_Closing event is not working?

查看:364
本文介绍了为什么MainWindow_Closing事件不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MainWindows和一个MainViewModel。

I have a MainWindows plus a MainViewModel.

MainViewModel _dataContext;
public MainWindow()
{
    InitializeComponent();
    Initialization();
    _dataContext = new MainViewModel();
    this.DataContext = _dataContext;
    _dataContext.ServerString =  "  Connected to Server " + ConfigurationManager.AppSettings["Server"];
}



现在我想通过点击窗口的红色x来关闭窗口。


Now I want to close the window by clicking the red x of the window.

void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
     try
     {
         cTokenSource.Cancel();
         e.Cancel = true;
         Application curApp = Application.Current;
         curApp.Shutdown();
      }



但是我发现代码没有达到此事件。为什么?


However I found that the code didn't reach this event. Why?

<Application x:Class="WpfLoadTesting.App"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             StartupUri="MainWindow.xaml">
    <Application.Resources>
    </Application.Resources>
</Application>

推荐答案

你可能没有绑定y我们对Closing事件的MainWindow_Closing方法。这有两种方法(使用其中一种,而不是两种方式)。



  • 来自XAML(在MainWindow.xaml中):

You probably haven't bound your MainWindow_Closing method to the Closing event. Here are two ways to do that (use one of them, not both).

  • From XAML (in MainWindow.xaml):
<Window ...

 Closing="MainWindow_Closing">



  • 来自C#代码(在构造函数中):


  • From the C# code (in the constructor):

    this.Closing += MainWindow_Closing;




  • 这篇关于为什么MainWindow_Closing事件不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆