Udostępnij za pośrednictwem


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);
        }
Private Sub AddButton(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
    sp1.Children.Clear()
    btn = New Button()
    btn.Content = "New Button"
    sp1.Children.Add(btn)
End Sub

Note

For the complete sample, see Using Elements Sample.

See Also

Concepts

Panels Overview

Reference

UIElementCollection

UIElement