How to add click handler to a button dynamically in Windows Phone?

By | March 26, 2012

Hello everyone….

This post is a simple example showing how to add eventHandlers to a button dynamically in windows phone or windows mobile.
We know programming for windows phone is done in C# or Visual Basic. Here I am going to explain in C#.

I assume that you have dragged a button control in your interface.
Then in the code do this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace Dynamic_Events
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            addEventHandler();
        }

        void addEventHandler()
        {
            button1.Click += new RoutedEventHandler(button1_Click);
        }

        void button1_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Button Clicked");
        }
    }
}

This is the line that adds the dynamic click handler to the button named “button1”.

button1.Click += new RoutedEventHandler(button1_Click);

Just type button1.Click” and hit two tabs and Visual Studio does the rest for you.

Leave your comments if you like this post.

Website Pin Facebook Twitter Myspace Friendfeed Technorati del.icio.us Digg Google StumbleUpon Premium Responsive

Leave a Reply

Your email address will not be published. Required fields are marked *