【问题标题】:WPF Programming, How to move an event to another class (outside)WPF 编程,如何将事件移动到另一个类(外部)
【发布时间】:2021-06-21 04:47:26
【问题描述】:

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

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

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 中的任何代码的情况下使用第二类中的事件。

【问题讨论】:

  • 最通用的解决方案可能是这个类似问题的最佳答案:stackoverflow.com/questions/7877532/… 但实际上它完全取决于您实际想要做什么以及为什么要避免代码隐藏代码。最简单的方法通常是咬紧牙关,在构造函数中处理事件路由。
  • 我的目标是在事件和视图之间进行切割,所以我想从项目内不同文件夹中的另一个类调用事件(事件)。需要有一个干净的 MainWindow.xaml.cs 没有任何事件。我的主要问题是如何以这种方式编写 xaml 代码,我可以从 differentClass 类调用事件,或者更好的情况是事件将在 differentClass 类中自动创建。感谢您的帮助
  • 你为什么想要这样一个目标?如果您在 XAML 设计器中附加事件处理程序,则处理程序方法将不可避免地在视图的类后面的代码中生成。这正是设计师的工作方式。然而,生成的处理程序方法可以委托给您喜欢的任何类或对象,因此不会包含超过一行代码。
  • 我希望在类中实现每个事件,其中包含事件的功能(方法)。例如,我希望将 login_button 的事件与登录本身放在同一个子文件夹中。

标签: c# wpf class events handler


【解决方案1】:

为此目的有一个 Behavior 类。您需要在项目中添加对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/>

【讨论】:

  • 此代码有效,但前提是事件代码存在于 MainWindow.xaml.cs 中。我的需要是 MainWindowXaml.cs 中没有事件,只有事件在第二类中。也许那是可能的。感谢您提供此解决方案。
  • 您可以/应该将CustomWindowHandlerBehavior 放到单独的文件中。它在没有 MainWindowXaml.cs 中的事件处理程序的情况下工作。您是否相应地调整了 XAML?
  • 是的,我添加了 xmlns:i 输入并将
  • 哪个Buton?? Window 的交互必须添加到 &lt;Window/&gt;,而不是按钮。请坚持你的问题,不要试图在一个问题上提出所有问题。
  • 为了尝试,我将它添加到 Window 并发生同样的错误。控制台写道:“MainWindow”不包含“{Event}”的定义,并且找不到接受“MainWindow”类型的第一个参数的可访问扩展方法“{Event}”(您是否缺少 using 指令或程序集引用?) {Event} 替换为特定事件处理程序名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多