how to trigger a button click in my code? [duplica

2020-07-22 18:14发布

How can I trigger a button click directly in my code?

I have a code like this:

namespace App1
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    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)
        {
            // ...
        }
    }
}

Is it possible to fire a click event von the button MyBtn? If yes how?

I know I can call the Button_Click method, but I want to call it over the button.

something like: MyBtn.FireClickEvent();

标签: c# windows-8
3条回答
We Are One
2楼-- · 2020-07-22 18:44

You can trigger the Button_Click event from the code as follows:

MyBtn.PerformClick();

You can try this one also:

MyBtn.Click(new object(), new EventArgs());
查看更多
家丑人穷心不美
3楼-- · 2020-07-22 18:47

You can remove the method link to your event(Click) :

MyBtn.Click -= new EventHandler(Button_Click);

And add an other method :

MyBtn.Click += new EventHandler(FireClickEvent);

So, when you will click the button, the method "FireClickEvent" will be called instead of "Button_Click".

To perform a click in the code :

MyBtn.PerformClick();
查看更多
4楼-- · 2020-07-22 19:06

I use this little extension to fire events from outside. It is kind of generic (can raise any event in any class) but I put it as a extension method to control only, since this is bad practice and I realy realy use it only if everything else fails. Have fun.

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);
        }

    }

}
查看更多
登录 后发表回答