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)


        {


            btnObject.RaiseEvent(


                new System.Windows.RoutedEventArgs(


                    System.Windows.Controls.Button.ClickEvent,


                    btnObject));


        }


3 comments:

Unknown

thanks, it was a great help!

Unknown

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

john

Awesome blog. I would love to see true life prepared to walk, so please share more informative updates. Great work keeps it up. 700-265 exam questions