WPF에서 버튼을 프로그래밍 방식으로 클릭하는 방법은 무엇입니까?
없으니깐.button.PerformClick()
WPF에서 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 이벤트 처리기를 호출하는 것입니다(또는 WPF-y 방식으로 작업하는 경우 버튼과 연결된 IC 명령 실행).
넌 이걸 왜 하는 거니?예를 들어, 자동화된 테스트를 수행하거나 버튼이 다른 코드 섹션에서 수행하는 것과 동일한 작업을 수행하려고 합니까?
그레그 D가 말했듯이, 저는 그 대안이Automation
MVVM 패턴(클릭 이벤트 발생 및 명령 실행)을 사용하여 버튼을 클릭하는 것은 다음을 호출하는 것입니다.OnClick
반사를 사용하는 방법:
typeof(System.Windows.Controls.Primitives.ButtonBase).GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(button, new object[0]);
버튼을 클릭하는 방법을 호출할 수도 있습니다.Button_Click(new object(), new RoutedEventArgs(ButtonBase.ClickEvent));
또 다른 방법은ButtonName.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
양쪽 모두 필요using System.Windows.Controls.Primitives;
Button_Click(new object(), new RoutedEventArgs(ButtonBase.ClickEvent));
ButtonName.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
MVVM 명령 패턴을 사용하여 버튼 기능(권장 사례)을 실행하는 경우 버튼의 효과를 트리거하는 간단한 방법은 다음과 같습니다.
someButton.Command.Execute(someButton.CommandParameter);
버튼이 트리거하는 Command 개체를 사용하고 XAML에 의해 정의된 Command Parameter를 전달합니다.
Automation API 솔루션의 문제는 Framework 어셈블리에 대한 참조가 필요하다는 것입니다.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);
}
}
}
언급URL : https://stackoverflow.com/questions/728432/how-to-programmatically-click-a-button-in-wpf
'programing' 카테고리의 다른 글
Mongoose 스키마에서 어레이 크기에 대한 제한을 설정하는 방법 (0) | 2023.05.23 |
---|---|
bash 스크립트의 조건인 경우 negate (0) | 2023.05.23 |
Python - YYY-MM-DD 형식의 문자열로 어제 날짜 가져오기 (0) | 2023.05.23 |
Xcode의 "헤더 검색 경로"와 "사용자 헤더 검색 경로" 중 어느 쪽입니까? (0) | 2023.05.18 |
SELECT*가 유해한 이유는 무엇입니까? (0) | 2023.05.18 |