0

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.

Luis
  • 1
  • This seems like a complicated way of setting a handler. Is there a reason why you have the name of a method in a string variable? – LBushkin Dec 22 '09 at 19:44

2 Answers2

1

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,421,763
  • 867
  • 9,128
  • 9,194
0

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

C# Dynamic Event Subscription

Community
  • 1
  • 1
Gabriel McAdams
  • 56,921
  • 12
  • 61
  • 77