Thursday, August 6, 2009

How To: Add Controls at Runtime in WPF

(WPF)Windows Presentation Foundation:

WPF development platform is built on a core programming system, which is extended to support a broad set of application development features, including the application model itself, resources, controls, graphics, layout, data binding, documents, and security.

Let's Start our Mission:

1- Create New WPF Application.
2- add Button from Toolbox.
3- add stackPanel from Toolbox.

the below Code will add three buttons at Runtime :

private void btnAddControl_Click(object sender, RoutedEventArgs e)
{
//Create three Buttons
for (int i = 0; i < 3; i++)
{
Button btnTest = new Button();
Thickness btnThickness = new Thickness();
btnTest.Content = "Button" + i;
btnTest.Name = "Button" + i;
btnThickness.Left = 0;
btnThickness.Top = 0;
btnTest.Margin = btnThickness;
btnTest.Width = 150;
btnTest.Height = 25;

//add Control to stack panel
stackPanel1.Children.Add(btnTest);
}
}

3 comments:

  1. thank you.... please explain how to remove created controls at runtime

    ReplyDelete
  2. (tipo de objeto, botão, entre outros) btn= stackPanel1.Children.OfType<(tipo de objeto, botão, entre outros)>().FirstOrDefault(btn => btn.Name == (Local onde conseguem Obter o nome do botão a eliminar));
    stackPanel1.Children.Remove(btn);"

    ReplyDelete