wpf中的button1.PerformClick()

为什么WPF中的这段代码不起作用?

private void button1_Click(object sender, EventArgs e) { MessageBox.Show("yes"); } private void Form1_Load(object sender, EventArgs e) { button1.PerformClick(); } 

我需要命令。

要使用Windows窗体应用程序的样式,您需要编写以下扩展方法:

 namespace System.Windows.Controls { public static class MyExt { public static void PerformClick(this Button btn) { btn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); } } } 

现在你可以将它用于任何按钮,假设一个名为“btnOK”的按钮:

 btnOK.PerformClick(); 

等等……有简单的方法。 如果您的按钮名称是button1并且button1单击了已订阅的事件,您将只调用该事件

 button1_Click(this,null); 

而不是PerformClick()使用RaiseEvent()

 private void button1_Click(object sender, EventArgs e) { MessageBox.Show("yes"); } private void Form1_Load(object sender, EventArgs e) { RoutedEventArgs newEventArgs = new RoutedEventArgs(Button.ClickEvent); button1.RaiseEvent(newEventArgs); } 

WPF中的好习惯是使用命令。 它提高了可测试性并分离了UI和业务逻辑。

首先,您可以尝试RoutedUICommand。

        

在代码隐藏文件中,我们必须定义RoutedClickCommand和Execute | CanExecute处理程序:

  public static ICommand RoutedClickCommand = new RoutedUICommand("ClickCommand", "ClickCommand", typeof(MainWindow)); private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("ololo"); } 

因此,当您需要按钮逻辑(样本中的“button1.PerformClick();”)时,只需输入下一行:

 MainWindow.RoutedClickCommand.Execute(null); 

至于我,我提出了另一种假设将命令带入演示模型的方法。 复合应用程序库(Prism)帮助我使用DelegateCommand类。 然后,演示模型中的命令定义如下所示:

  private DelegateCommand _clickCommand; public ICommand ClickCommand { get { if (this._clickCommand == null) { this._clickCommand = new DelegateCommand(p => { //command logic }, p => { // can execute command logic }); } return this._clickCommand; } } 

并查看XAML和代码:

     

 public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.Model = new SampleModel(); } protected SampleModel Model { get { if (this.Model.ClickCommand.CanExecute()) { this.Model.ClickCommand.Execute(); } return (SampleModel)this.DataContext; } set { this.DataContext = value; } } } 

下一个代码在视图中调用命令绕过单击按钮:

 if (this.Model.ClickCommand.CanExecute()) { this.Model.ClickCommand.Execute(); } 

本博客推荐的Adam Nathans WPF Unleashed的摘录。
Imho是最好的,如果不是最好的WPF参考。

 var bap = new System.Windows.Automation.Peers.ButtonAutomationPeer(someButton); var iip = bap.GetPattern(System.Windows.Automation.Peers.PatternInterface.Invoke) as System.Windows.Automation.Provider.IInvokeProvider; iip.Invoke(); 

我认为解决问题的最短,最有效的解决方案只需一行即可完成。

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

这适用于WPF C#

因为PerformClick是WindowsForms Button控件上的一个方法:

http://msdn.microsoft.com/en-us/library/system.windows.forms.button.performclick.aspx

不在WPF Button控件上:

http://msdn.microsoft.com/en-us/library/system.windows.controls.button_methods.aspx

要自动执行按钮单击,您可能希望查看UI自动化框架:

http://msdn.microsoft.com/en-us/library/ms747327.aspx