How to programmatically click a button in WPF?

前端 未结 8 963
情深已故
情深已故 2020-11-28 02:00

Since there\'s no button.PerformClick() method in WPF, is there a way to click a WPF button programmatically?

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 02:02

    if you want to call click event:

    SomeButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
    

    And if you want the button looks like it is pressed:

    typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { true });
    

    and unpressed after that:

    typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { false });
    

    or use the ToggleButton

提交回复
热议问题