簡體   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