This documentation is archived and is not being maintained.

How to: Add an Element Dynamically

This example shows how to add a Button element to a StackPanel by using the Add method of the Children property.

The following Extensible Application Markup Language (XAML) example creates a TabControl. When a user clicks the Add Control tab, a MouseLeftButtonDown event handler, AddButton, which is written in code, clears any existing controls and adds a new button.

Example

<TabControl>
<TabItem MouseLeftButtonUp="AddButton">
<TabItem.Header>Add Control</TabItem.Header>
</TabItem>

void AddButton(object sender, MouseButtonEventArgs e)
{
    sp1.Children.Clear();
    btn = new Button();
    btn.Content = "New Button";
    sp1.Children.Add(btn);
}

NoteNote:

For the complete sample, see Using Elements Sample.

See Also

Show: