Windows 8 Button click programmatically in C# and

2019-07-20 17:57发布

问题:

I want to click button programatically in C# xaml. As I found that there is no method like PerformClick. What else is the alternative for it.

Actually I have set of 10 buttons with x:Name like btn1, btn2, btn3 etc... I have a number from 1 to 10 based on that number I need to click these buttons. I was planning to get the control by using

ParentControl.FindName('btn' + number)

and then fire the event from that. But since there is no PerformClick method in Windows 8 C# hence i need an alternative for this.

Raiseevent

回答1:

Here's how to do it...

Let's say you have this button defined in your XAML file:

<Button Grid.Column="0" Grid.Row="0" x:Name="DefaultSnooze" Content="Default Snooze" Click="SendToast_Click" Height="34" Width="134"/>

Then do this in your code behind where you want the Click event handler code to be fired programmatically:

ButtonAutomationPeer peer = new ButtonAutomationPeer(DefaultSnooze);

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

I tested it right now and it works beautifully. :)


Source: How to programmatically click a button



回答2:

You should be able to use:

RaiseEvent(new RoutedEventArgs(Button.ClickEvent, myButton));

In the code-behind of a XAML view.

RaiseEvent is available on any UIElement-derived class.