How to Dynamically Add Controls to Windows Phone Page ?

Some times , we may need to create controls on the Windows Phone Page dynamically .

In this example , i use the container Stack Panel and add the controls to the Stack Panel .

The Stack panel in Windows Phone is a control used to stack controls on each other.

1. Create a new Windows Phone 7 Silverlight Application and Delete the Default StackPanel inside the Grid “LayoutRoot” .

This StackPanel is titled “TitlePanel” and includes 2 Text Blocks .

2. In the Grid “ContentPanel” , Drag and Drop the StackPanel to the ContentPanel and name it as “StackPanel1”. Note that we can use the ContentPanel too to add the controls but we take the StackPanel for the Demo here .
3. Go to the Code behind file , and create a function to add controls on the StackPanel1 . In this Example , i will create a TextBox and a Button .The StackPanel includes a Method Children.Add defined in the PresentationFrameworkCollection class .One can use this method to add the controls to StackPanel .

public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
CreateControls();
}
private void CreateControls()
{
TextBlock txtName = new TextBlock();
txtName.Text = "@isenthil";
Button btnClick = new Button();
btnClick.Content = "Click";
btnClick.Click += new RoutedEventHandler(btnClick_Click);
StackPanel1.Children.Add(txtName);
StackPanel1.Children.Add(btnClick);
}
void btnClick_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("You Clicked Button");
}
}

4. Call the Above method in the Construtor of the MainPage and Run the Application . You should immediately see the Page with a textbox and Button

How to Dynamically Add Controls to Windows Phone Page ?

How to Dynamically Add Controls to Windows Phone Page ?

3 Comments

  1. Tanmay October 5, 2014 Reply
    • Senthil Kumar October 5, 2014 Reply
  2. Mehar September 5, 2015 Reply

Leave a Reply