Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

button1.PerformClick() in wpf

Tags:

c#

wpf

Why this code in WPF does not work ?

private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("yes");
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        button1.PerformClick();
    }

I need to command.

like image 853
visual2020 Avatar asked Jan 19 '11 11:01

visual2020


2 Answers

To use the windows form application's style, you need to write the following extension method:

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

now you can use it for any button, assuming a button called "btnOK":

btnOK.PerformClick();
like image 180
logicChild Avatar answered Oct 06 '22 06:10

logicChild


Wait.. there is simple way. if your button name is button1 and button1 click event already subscribed,you will just call that event like

button1_Click(this,null);
like image 33
Mustafa Ekici Avatar answered Oct 06 '22 07:10

Mustafa Ekici