Windows 8 Button click programmatically in C# and Xaml

早过忘川 提交于 2019-12-11 01:56:38

问题


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.



来源:https://stackoverflow.com/questions/12509908/windows-8-button-click-programmatically-in-c-sharp-and-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!