I would like to pass a reference of a method into another method and store it as a variable. Later, I would like to use this reference to define an event handler.
When making an event handler, a method reference is passed like:
myButton.Click += new RoutedEventHandler(myButton_Click);
And if you look at the constructor for ‘RoutedEventHandler’ from intelliSense, it looks like:
RoutedEventHandler(void(object, RoutedEventArgs))
What I would like to do is pass the method ‘myButton_Click’ to a different static method and then create an event handler there. How do I pass the reference to the static method? I tried the following but it doesn’t compile:
public class EventBuilder { private static void(object, RoutedEventArgs) _buttonClickHandler; public static void EventBuilder(void(object, RoutedEventArgs) buttonClickHandler) { _buttonClickHandler = buttonClickHandler; } public static void EnableClickEvent() { myButton.Click += new RoutedEventHandler(_buttonClickHandler); } }
Thanks, Ben
To reference a Method Reference (called a delegate in .NET), use the Handler name, rather than the signature.