Reputation: 23
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. 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.
Upvotes: 0
Views: 696
Reputation: 61349
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; you'll need an actual method (as described by @hoodaticus).
If this is in 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).
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). Then you can use CommandParameter
to get the custom piece of data into the handler.
Upvotes: 1
Reputation: 3880
MyEvent
is unnecessary here as you are not creating your own event, just subscribing to someone else's. The delegate
keyword declares a method signature and return type - it does not create instances or define method bodies.
Here is how you re-use a lambda expression:
Action<object, RoutedEventArgs> myHandler = (o, e) =>
{
/* write event handler code here, you must */
};
btn1.Click += myHandler;
btn2.Click += myHandler;
Upvotes: 1