How to simulate the click of a button via code?

Asked

Viewed 2,266 times

3

Buttons in WPF applications do not have the Button.PerformClick. So how could I simulate the click of a button via code?

1 answer

3


Use the method RaiseEvent of your Button, as example: created a BtnExemplo and BtnChamar and on the button you need to call BtnExemplo:

private void BtnChamar_Click(object sender, RoutedEventArgs e)
{
    BtnExemplo.RaiseEvent(e);
}

An elegant shape could use extension method, create a classe with the code below:

using System.Windows.Controls;

namespace WpfApplication1
{
    public static class MyExt
    {
        public static void PerformClick(this Button btn)
        {
            btn.RaiseEvent(new System.Windows.RoutedEventArgs(Button.ClickEvent, btn));
        }
    }
}

and now the method PerformClick will be available and can use:

private void BtnChamar_Click(object sender, RoutedEventArgs e)
{
    BtnExemplo.PerformClick();
}

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.