How to programmatically click a button in WPF?

前端 未结 8 949
情深已故
情深已故 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条回答
  •  难免孤独
    2020-11-28 02:03

    The problem with the Automation API solution is, that it required a reference to the Framework assembly UIAutomationProvider as project/package dependency.

    An alternative is to emulate the behaviour. In the following there is my extended solution which also condiders the MVVM-pattern with its bound commands - implemented as extension method:

    public static class ButtonExtensions
    {
        /// 
        /// Performs a click on the button.
    /// This is the WPF-equivalent of the Windows Forms method "". /// This simulates the same behaviours as the button was clicked by the user by keyboard or mouse:
    /// 1. The raising the ClickEvent.
    /// 2.1. Checking that the bound command can be executed, calling , if a command is bound.
    /// 2.2. If command can be executed, then the will be called and the optional bound parameter is p ///
    ///
    /// The source button. /// sourceButton public static void PerformClick(this Button sourceButton) { // Check parameters if (sourceButton == null) throw new ArgumentNullException(nameof(sourceButton)); // 1.) Raise the Click-event sourceButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent)); // 2.) Execute the command, if bound and can be executed ICommand boundCommand = sourceButton.Command; if (boundCommand != null) { object parameter = sourceButton.CommandParameter; if (boundCommand.CanExecute(parameter) == true) boundCommand.Execute(parameter); } } }

提交回复
热议问题