MahApps Metro capture close window event

Viewed 4213

I'm using the MahApps Metro window style, and I want to capture the event when the user clicks on the close button of the window.

I've set my ShutdownMode to OnExplicitShutdown so I need to call Application.Current.Shutdown(); when that button is clicked

How can I do this ?

4 Answers

I believe that I am also trying to do the same thing as you (bind to the close window button) using WPF and MahApps.Metro. I wasn't able to find a way yet to bind to that command explicitly, but I was able to accomplish this by setting the ShowCloseButton property to false (to hide it) and then created my own close window command button and handled the logic in my viewmodel. Took me some digging, but I found that you can easily add your own window command controls in the command bar with MahApps.Metro just add similar markup to your XAML:

<Controls:MetroWindow.WindowCommands>
    <Controls:WindowCommands>
        <Button Content="X" Command="{Binding CancelCommand}" />
    </Controls:WindowCommands>
</Controls:MetroWindow.WindowCommands>

You can use "Closing" or "Closed" event

Closing handler gets triggered when user clicks on the Close button. This also gives you control on whether the application should be closed.

Similarly, Closed handler gets triggered just before the window is closed

<Controls:MetroWindow x:Class="MyClass.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
Title="My Class"
Closing="MainWindow_OnClosing">
</Controls:MetroWindow>
Related