Saeed mohammadi
Saeed mohammadi

Reputation: 319

Handle closing event of all windows in wpf

In WPF for registering an event for all window something like this should written in App class :

EventManager.RegisterClassHandler(typeof(Window), Window.PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));

But Window class does not have any property for handling Closing event

Upvotes: 0

Views: 571

Answers (2)

Robert
Robert

Reputation: 2523

Window does have a Closing event that you can cancel but it is not RoutedEvent so you cannot subscribe to it in this fashion.

You can always inherit the Window and subscribe to closing in one place. All inheriting Windows will inherit this behavior also.

EDIT

This can be done with behaviors as well. Make sure you install a NuGet package called Expression.Blend.Sdk. Than create an attached behavior like so:

using System.Windows;
using System.Windows.Interactivity;

namespace testtestz
{
    public class ClosingBehavior : Behavior<Window>
    {
        protected override void OnAttached()
        {
            AssociatedObject.Closing += AssociatedObject_Closing;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.Closing -= AssociatedObject_Closing;
        }

        private void AssociatedObject_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = MessageBox.Show("Close the window?", AssociatedObject.Title, MessageBoxButton.OKCancel) == MessageBoxResult.Cancel;
        }
    }
}

Than in your XAML add this behavior like so:

<Window x:Class="testtestz.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        xmlns:local="clr-namespace:testtestz"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
    <i:Interaction.Behaviors>
        <local:ClosingBehavior/>
    </i:Interaction.Behaviors>
    <Grid>
    </Grid>
</Window>

Upvotes: 1

pjrki
pjrki

Reputation: 248

What about registering to the Unloaded event? which has it's own property. For example:

EventManager.RegisterClassHandler(typeof(Window), PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));
EventManager.RegisterClassHandler(typeof(Window), UnloadedEvent, new RoutedEventArgs( ... ));

Upvotes: 0

Related Questions