繁体   English   中英

如何以编程方式单击 WPF 中的按钮?

[英]How to programmatically click a button in WPF?

由于 WPF 中没有button.PerformClick()方法,有没有办法以编程方式单击 WPF 按钮?

就像 JaredPar 所说的,你可以参考 Josh Smith 的关于自动化的文章。 但是,如果您查看对他的文章的评论,您会发现针对 WPF 控件引发事件的更优雅方式

someButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));

我个人更喜欢上面的一个而不是自动化同行。

WPF 在这里采用与 WinForms 略有不同的方法。 他们没有将对象的自动化内置到 API 中,而是为每个负责自动化它的对象提供一个单独的类。 在这种情况下,您需要ButtonAutomationPeer来完成此任务。

ButtonAutomationPeer peer = new ButtonAutomationPeer(someButton);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv.Invoke();

是一篇关于这个主题的博客文章。

注: IInvokeProvider接口在定义UIAutomationProvider组装。

如果你想调用点击事件:

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

如果您希望按钮看起来像被按下:

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

之后没有按下:

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

或使用切换按钮

this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

如果您可以访问源代码,则以编程方式“单击”按钮的一种方法是简单地调用按钮的 OnClick 事件处理程序(或执行与按钮关联的 ICommand,如果您以更 WPF-y 的方式进行操作) )。

你为什么做这个? 例如,您是在进行某种自动化测试,还是尝试执行与按钮在不同代码部分执行的操作相同的操作?

正如Greg D所说,我认为使用 MVVM 模式(单击事件引发并执行命令)单击按钮的Automation的替代方法是使用反射调用OnClick方法:

typeof(System.Windows.Controls.Primitives.ButtonBase).GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(button, new object[0]);

Button函数使用MVVM Command模式时(推荐做法),一个简单的触发Button效果的方法如下:

someButton.Command.Execute(someButton.CommandParameter);

这将使用按钮触发的Command对象并传递XAML定义的CommandParameter

自动化 API 解决方案的问题在于,它需要引用框架程序集UIAutomationProvider作为项目/包依赖项。

另一种方法是模仿行为。 下面是我的扩展解决方案,它也考虑了 MVVM 模式及其绑定命令 - 作为扩展方法实现:

public static class ButtonExtensions
{
    /// <summary>
    /// Performs a click on the button.<br/>
    /// This is the WPF-equivalent of the Windows Forms method "<see cref="M:System.Windows.Forms.Button.PerformClick" />".
    /// <para>This simulates the same behaviours as the button was clicked by the user by keyboard or mouse:<br />
    /// 1. The raising the ClickEvent.<br />
    /// 2.1. Checking that the bound command can be executed, calling <see cref="ICommand.CanExecute" />, if a command is bound.<br />
    /// 2.2. If command can be executed, then the <see cref="ICommand.Execute(object)" /> will be called and the optional bound parameter is p
    /// </para>
    /// </summary>
    /// <param name="sourceButton">The source button.</param>
    /// <exception cref="ArgumentNullException">sourceButton</exception>
    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);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM