views:

42

answers:

2

Hi

I have a String like this:

string myEventName = "myButton_Click";

Then I need to create an EventHandlers for the click of some button, but passing the String as a parameter, the "myButton_Click" method already exists:

private void myButton_Click (object sender, RoutedEventArgs e) { }

Is this possible, using reflection or other kind of trick?

Thanks.

+1  A: 

Yes, you can use reflection. It's fairly ugly, but it should work:

// Here, "target" is the instance you want to use when calling
// myButton_Click, and "button" is the button you want to
// attach the handler to.
Type type = target.GetType();
MethodInfo method = type.GetMethod(myEventName,
    BindingFlags.Instance | BindingFlags.NonPublic);
EventHandler handler = (EventHandler) Delegate.CreateInstance(
    typeof(EventHandler), target, method);
button.Click += handler;

You'll need a lot of error checking of course, but that's the basic procedure. By the way, your variable would be better named as "myHandlerName" or something similar - it's not the event itself.

Jon Skeet
+1 for bringing up naming convention ... it's always helpful to know how we should be naming things
Chris Nicol
A: 

You can do this by using reflection. Take a look at these 2 links to give you all that you need to know:

http://msdn.microsoft.com/en-us/library/ms228976.aspx

http://stackoverflow.com/questions/45779/c-dynamic-event-subscription

Gabriel McAdams