Wednesday, August 13, 2008

Click a Wpf Button in code

Need to click a button in wpf from the code behind? It's not quite as intuitive as the old Windows Forms way, but it is more powerful since it would appear you can raise any event now (or most at least). In this case, you could omit the btnLaunch param on the RoutedEventArgs, but I added it in for clarity.

System.Windows.Controls.Button btnLaunch = new Button();

btnLaunch.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, btnLaunch));

Since I love the new 3.5 Extensions, I've made an extension method that mimics the old Windows Forms method.

        /// <summary>

        /// Manally performs a <seealso cref="System.Windows.Controls.Button.Click"/> event for a supplied

        /// <seealso cref="System.Windows.Controls.Button"/>.

        /// </summary>

        /// <param name="btnObject">The <seealso cref="System.Windows.Controls.Button"/> object to

        /// be clicked.</param>

        public static void PerformClick(this System.Windows.Controls.Button btnObject)



                new System.Windows.RoutedEventArgs(






thanks, it was a great help!

Mahdi Babaei

this.PowerButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));