1

我正在尝试通过反射获得按钮事件点击。我想获取“Btn_AddTest_Click”字符串以将其分配给 CommandBinding。例如:

XAML

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

在后面

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

和功能:

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

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

但是“eventsProperty”返回 Null,我尝试使用“Events”、“EventClick”、“Click”......同样的返回。

我受到这篇文章的启发

4

1 回答 1

1

我相信您需要查看按钮的 RoutedEvents。这将为您提供Click路由事件:

        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();

并调用它:

clickEvent.Handler.DynamicInvoke(null, null);
于 2017-06-26T05:21:06.827 回答