WPF 编程,如何将一个事件移动到另一个 class(外部)

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

我有一个问题,我想将 XAML 中的一个事件直接添加到另一个 class。 使用的标准 class 是 MainWindow。

在我的情况下,我想定义事件应该使用哪个 class。

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)
    {
    }
}

也许有人可以帮助我,我如何在 MainWindow 中不使用任何代码的情况下使用第二个 class 中的事件。

有一个行为 class 可用于此目的。您需要在项目中添加对 System.Windows.Interactivity 的引用: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)
    {
        //...
    }
}

在 XAML 中使用此行为:

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