C# 如何以编程方式单击 WPF 中的按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/728432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically click a button in WPF?
提问by tghoang
Since there's no button.PerformClick()
method in WPF, is there a way to click a WPF button programmatically?
由于button.PerformClick()
WPF 中没有方法,有没有办法以编程方式单击 WPF 按钮?
采纳答案by JaredPar
WPF takes a slightly different approach than WinForms here. Instead of having the automation of a object built into the API, they have a separate class for each object that is responsible for automating it. In this case you need the ButtonAutomationPeer
to accomplish this task.
WPF 在这里采用与 WinForms 略有不同的方法。他们没有将对象的自动化内置到 API 中,而是为每个负责自动化的对象提供一个单独的类。在这种情况下,您需要ButtonAutomationPeer
完成此任务。
ButtonAutomationPeer peer = new ButtonAutomationPeer(someButton);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv.Invoke();
Hereis a blog post on the subject.
这是一篇关于这个主题的博客文章。
Note: IInvokeProvider
interface is defined in the UIAutomationProvider
assembly.
注意:IInvokeProvider
接口是在UIAutomationProvider
程序集中定义的。
回答by Greg D
One way to programmatically "click" the button, if you have access to the source, is to simply call the button's OnClick event handler (or Execute the ICommand associated with the button, if you're doing things in the more WPF-y manner).
如果您可以访问源代码,则以编程方式“单击”按钮的一种方法是简单地调用按钮的 OnClick 事件处理程序(或执行与按钮关联的 ICommand,如果您以更 WPF-y 的方式进行操作) )。
Why are you doing this? Are you doing some sort of automated testing, for example, or trying to perform the same action that the button performs from a different section of code?
你为什么做这个?例如,您是在进行某种自动化测试,还是尝试执行与按钮在不同代码部分执行的操作相同的操作?
回答by Denis Vuyka
Like JaredPar said you can refer to Josh Smith's article towards Automation. However if you look through comments to his article you will find more elegant way of raising events against WPF controls
就像 JaredPar 所说的,你可以参考 Josh Smith 的关于自动化的文章。但是,如果您查看对他的文章的评论,您会发现针对 WPF 控件引发事件的更优雅的方式
someButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
I personally prefer the one above instead of automation peers.
我个人更喜欢上面的一个而不是自动化同行。
回答by Sonorx
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
或使用切换按钮
回答by Mahdi
this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
回答by Max
As Greg Dsaid, I think that an alternative to Automation
to click a button using the MVVM pattern (click event raised and command executed) is to call the OnClick
method using reflection:
正如Greg D所说,我认为Automation
使用 MVVM 模式(单击事件引发并执行命令)单击按钮的替代OnClick
方法是使用反射调用该方法:
typeof(System.Windows.Controls.Primitives.ButtonBase).GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(button, new object[0]);
回答by KVKConsultancy
When using the MVVMCommand pattern for Buttonfunction (recommended practice), a simple way to trigger the effect of the Buttonis as follows:
Button函数使用MVVMCommand模式时(推荐做法),一个简单的触发Button效果的方法如下:
someButton.Command.Execute(someButton.CommandParameter);
This will use the Commandobject which the button triggers and pass the CommandParameterdefined by the XAML.
这将使用按钮触发的Command对象并传递XAML定义的CommandParameter。
回答by rittergig
The problem with the Automation API solution is, that it required a reference to the Framework assembly UIAutomationProvider
as project/package dependency.
自动化 API 解决方案的问题在于,它需要引用框架程序集UIAutomationProvider
作为项目/包依赖项。
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:
另一种方法是模仿行为。下面是我的扩展解决方案,它也考虑了 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);
}
}
}