Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a MainWindows plus a MainViewModel.
C#
MainViewModel _dataContext;
public MainWindow()
{
    InitializeComponent();
    Initialization();
    _dataContext = new MainViewModel();
    this.DataContext = _dataContext;
    _dataContext.ServerString =  "  Connected to Server " + ConfigurationManager.AppSettings["Server"];
}

Now I want to close the window by clicking the red x of the window.
C#
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?
XML
<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>
Posted
Comments
Thomas Daniels 10-Nov-14 10:59am    
Have you bound the Closing event to the MainWindow_Closing method?
[no name] 10-Nov-14 11:02am    
Perhaps not. How and where?
Thomas Daniels 10-Nov-14 11:14am    
I have posted an answer to show how you can bind it.

1 solution

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):
    XML
    <Window ...
     Closing="MainWindow_Closing">

  • From the C# code (in the constructor):
    C#
    this.Closing += MainWindow_Closing;

 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900