Search code examples
c#wpfclasseventshandler

WPF Programming, How to move an event to another class (outside)


I have the problem that I want to add an event from XAML directly to another class. The standard class, which is used, is the MainWindow.

In my situation I want to define, which class should be used for the event.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    private void Window_Closing_Event(object sender, System.ComponentModel.CancelEventArgs e)
    {
    }
}

public class differentClass
{
    public differentClass()
    {
    }
    private void Window_Closing_Event(object sender, System.ComponentModel.CancelEventArgs e)
    {
    }
}

Maybe someone can help me, how I can use the event from the second class without any code in the MainWindow.


Solution

  • There is a Behavior class for this purpose. You will need to add the reference to the System.Windows.Interactivity in the project: How to add System.Windows.Interactivity to project?

    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Interactivity;
    
    public class CustomWindowHandlerBehavior: Behavior<Window>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Closing+= Window_Closing_Event;
        }
    
        protected override void OnDetaching()
        {
            AssociatedObject.Closing-= Window_Closing_Event;
            base.OnDetaching();
        }
    
        private void Window_Closing_Event(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //...
        }
    }
    

    using this behavior in XAML:

    <Window
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
        <i:Interaction.Behaviors>
            <local:CustomWindowHandlerBehaviour />
        </i:Interaction.Behaviors>
    <Window/>