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.

How to Dynamically Add Controls to Windows Phone Page ?

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 ?

    2 Comments

  1. October 5, 2014
    Reply

    What is the error message that you get when running this code ?

  2. Mehar
    September 5, 2015
    Reply

    how can i save this button so that when app restart again it shows the dynamically generated button?

Leave A Reply

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

You May Also Like

In this post, you’ll learn about the Win32 Error “0x000019E5 – ERROR_COULD_NOT_RESIZE_LOG” that you get when debugging system erors in...
In this post, you’ll learn about the error “CO_E_DBERROR 0x8004E02B” that is returned when working with COM based APIs or...
In this post, you’ll learn about the Win32 Error “0x000019D0 – ERROR_LOG_BLOCK_VERSION” that you get when debugging system erors in...