Csharp/C#教程:如何触发我的代码中的按钮单击?分享


如何触发我的代码中的按钮单击?

如何直接在我的代码中触发按钮单击?

我有这样的代码:

namespace App1 { ///  /// An empty page that can be used on its own or navigated to within a Frame. ///  public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { // fire a click ebent von the "Button" MyBtn } private void Button_Click(object sender, RoutedEventArgs e) { // ... } } } 

是否可以通过按钮MyBtn触发点击事件? 如果有,怎么样?

我知道我可以调用Button_Click方法,但我想通过按钮调用它。

类似于: MyBtn.FireClickEvent();

您可以从代码中触发Button_Click事件,如下所示:

 MyBtn.PerformClick(); 

你也可以尝试这个:

 MyBtn.Click(new object(), new EventArgs()); 

您可以删除事件的方法链接(单击):

 MyBtn.Click -= new EventHandler(Button_Click); 

并添加其他方法:

 MyBtn.Click += new EventHandler(FireClickEvent); 

因此,当您单击按钮时,将调用方法“FireClickEvent”而不是“Button_Click”。

要在代码中执行单击:

 MyBtn.PerformClick(); 

我使用这个小扩展来从外部发射事件。 它是一种通用的(可以在任何类中引发任何事件),但我把它作为一个扩展方法来控制,因为这是不好的做法,我真的真的只在其他一切都失败时才使用它。 玩得开心。

上述就是C#学习教程:如何触发我的代码中的按钮单击?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 public static class ControlExtensions { public static void SimulateClick(this Control c) { c.RaiseEvent("Click", EventArgs.Empty); } public static void RaiseEvent(this Control c, string eventName, EventArgs e) { // TO simulate the delegate invocation we obtain it's invocation list // and walk it, invoking each item in the list Type t = c.GetType(); FieldInfo fi = t.GetField(eventName, BindingFlags.NonPublic | BindingFlags.Instance); MulticastDelegate d = fi.GetValue(c) as MulticastDelegate; Delegate[] list = d.GetInvocationList(); // It is important to cast each member to an appropriate delegate type // For example for the KeyDown event we would replace EventHandler // with KeyEvenHandler and new EventArgs() with new KeyHandlerEventArgs() foreach (EventHandler del in list) { del.Invoke(c, e); } } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/959942.html

(0)
上一篇 2021年11月24日
下一篇 2021年11月24日

精彩推荐