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.

2 thoughts on “How to add click handler to a button dynamically in Windows Phone?

  1. http://codigodelbonusreferido.es/

    Hello! Someone in my Facebook group shared this website with us so I
    came to look it over. I’m definitely loving the information. I’m book-marking and will be
    tweeting this to my followers! Excellent blog
    and excellent design and style.

    Reply
  2. gry online hazardowe automaty

    I got this web site from my pal who shared with me on the topic of this web page and now this time I
    am visiting this web page and reading very informative articles or
    reviews at this place.

    Reply

Leave a Reply to gry online hazardowe automaty Cancel reply

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