tags:

views:

1882

answers:

4

Since there's no button.PerformClick() in WPF, is there a way to click a wpf button programmatically?

A: 

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).

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?

Greg D
It's not the only solution to my problem, but when I tried to do this, I found that it's not as easy as button.PerformClick(), so just a bit curious... :)
tghoang
+5  A: 

WPF takes a slighly 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.

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

Here is a blog post on the subject: http://joshsmithonwpf.wordpress.com/2007/03/09/how-to-programmatically-click-a-button/

JaredPar
Thank you, I did search google, but could not access the link at that time :)
tghoang
Slick, I wasn't aware of this. Could be very useful for automated testing. Note that there's a comment on that link which suggests using a provided factory to get the automation peer instead of creating one yourself.
Greg D
+4  A: 

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

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

I personally prefer the one above instead of automation peers.

Denis Vuyka
The RaiseEvent solution only raises the event. It does not execute the Command associated with the Button (as Skanaar say)
Eduardo Molteni
If you use XAML eg <Button Name="X" Click="X_Click" />, the event will be caught by the on click handler as per normal. +1 from me!
metao
A: 

The RaiseEvent solution only raises the event. It does not execute the Command associated with the Button.

Skanaar