1

I'm trying to get button eventclick with reflexion. I would like to get "Btn_AddTest_Click" string for assign it to a CommandBinding. For example:

XAML

<Button x:Name="Btn_Add"
    Click="Btn_AddTest_Click"/>

Behind

public async void Btn_AddTest_Click(object sender, RoutedEventArgs e)
{...}

And function:

Type ObjType = Btn_Add.GetType();
PropertyInfo eventsProperty = ObjType.GetProperty("Events", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);

EventHandlerList events = (EventHandlerList)eventsProperty.GetValue(Btn_Add, null);

But "eventsProperty" return Null, i tried with "Events", "EventClick", Click"... same return.

I got inspired by this post

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
Marc
  • 107
  • 8

1 Answers1

1

I believe you need to look at the RoutedEvents for the button. This will get you the Click routed event:

        var eventStore = Btn_Add
            .GetType()
            .GetProperty("EventHandlersStore", BindingFlags.Instance | BindingFlags.NonPublic)
            .GetValue(Btn_Add, null);

        var clickEvent = ((RoutedEventHandlerInfo[])eventStore
            .GetType()
            .GetMethod("GetRoutedEventHandlers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
            .Invoke(eventStore, new object[] { Button.ClickEvent }))
            .First();

And to invoke it:

clickEvent.Handler.DynamicInvoke(null, null);
Lockdowne
  • 474
  • 3
  • 7
  • thank you so much, i find 'Btn_AddTest_Click' in "clickEvent.Handler.Method.Name;" but i can't convert this to ExecutedRoutedEventHandler for CommandBinding NewCommandBinding = new CommandBinding(NewCommand, Btn_AddTest_Click); – Marc Jun 26 '17 at 07:45
  • Was not the same subject, I asked my second question here https://stackoverflow.com/questions/44760585/how-get-commandbinding-executed-from-routedeventhandlerinfo Thank again Lockdowne – Marc Jun 26 '17 at 14:39