简体   繁体   English

在C#中重用委托事件的正确方法

[英]Proper way to reuse delegate events in c#

I am trying to see if I can use delegate events and reuse them so that I do not have to make multiple click events. 我正在尝试查看是否可以使用委托事件并重用它们,以便不必进行多次单击事件。 Right now I have the following... 现在我有以下...

namespace EventsWPF
{

public partial class MainWindow : Window
{
    public delegate void MyEvent(object sender, RoutedEventArgs e); 

    public MainWindow()
    {
        InitializeComponent();
        btn1.Click += MyEvent;
        btn2.Click += MyEvent;
    }


}

} }

Is this the correct way to do it? 这是正确的方法吗? Or am I thinking about this the wrong way? 还是我在想这是错误的方式? I know you can use Lambda expressions as an event handler. 我知道您可以将Lambda表达式用作事件处理程序。 But if I have multiple events I don't want to create multiple Lamda expressions for each handler when I can just reuse a delegate. 但是,如果我有多个事件,当我可以重用委托时,我不想为每个处理程序创建多个Lamda表达式。

Yes, if two buttons should have the same exact logic run; 是的,如果两个按钮应该具有完全相同的逻辑运行; then attaching the same handler is perfectly fine . 然后附加相同的处理程序就很好了 You won't be able to do it by attaching a delegate type though; 但是,您将无法通过附加delegate类型来完成此操作; you'll need an actual method (as described by @hoodaticus). 您将需要一个实际的方法(如@hoodaticus所述)。

If this is in WPF: 如果在WPF中:

Usually however, two buttons don't do the same thing and you can't get away with this. 但是通常情况下,两个按钮不会执行相同的操作,因此您无法逃避。 Far more commonly, two buttons do the same thing but with different arguments. 更常见的是,两个按钮执行相同的操作,但参数不同。 Unfortunately, a WinForms style approach will be very painful here (you can check against sender but.... ewww). 不幸的是,这里的WinForms样式方法将非常痛苦(您可以检查sender但... ewww)。

In that case (actually, in all cases) you really want to take advantage of the MVVM pattern and set up commands for your buttons (not click handlers). 在那种情况下(实际上,在所有情况下),您确实想利用MVVM模式并为按钮(而不是单击处理程序)设置命令。 Then you can use CommandParameter to get the custom piece of data into the handler. 然后,您可以使用CommandParameter将自定义数据片段放入处理程序中。

MyEvent is unnecessary here as you are not creating your own event, just subscribing to someone else's. MyEvent在这里是不必要的,因为您不是在创建自己的事件,而是订阅其他人的事件。 The delegate keyword declares a method signature and return type - it does not create instances or define method bodies. delegate关键字声明方法签名和返回类型-它不会创建实例或定义方法主体。

Here is how you re-use a lambda expression: 这是重用lambda表达式的方式:

Action<object, RoutedEventArgs> myHandler = (o, e) => 
{ 
    /* write event handler code here, you must */  
};

btn1.Click += myHandler;
btn2.Click += myHandler;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM