views:

955

answers:

2

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

A: 

try

private static delegate void(object sender, RoutedEventArgs e) _buttonClickHandler;
Jacob Adams
+5  A: 

To reference a Method Reference (called a delegate in .NET), use the Handler name, rather than the signature.

public class EventBuilder
{
    private static RoutedEventHandler _buttonClickHandler;

    public EventBuilder(RoutedEventHandler buttonClickHandler)
    {
        _buttonClickHandler = buttonClickHandler;
    }

    public static void EnableClickEvent()
    {
        myButton.Click += new RoutedEventHandler(_buttonClickHandler);
    }
}
bdukes
if _buttonClickHandler is already a RoutedEventHandler, shouldn't I be able to just set it like myButton.Click += _buttonClickHandler?
Ben McIntosh
Yes, that is correct. Even in general usage, you can leave off the "new EventHandler(...)" syntax; i.e. myButton.Click += myButton_Click; is valid by itself.
bdukes