How to: Remove the Child Nodes of an Element

This example describes how to remove all elements in the UIElementCollection using the Clear method.

The following Extensible Application Markup Language (XAML) example creates a TabControl. When the user clicks the Clear Controls tab, a MouseLeftButtonDown event handler, ClearButtons, written in C# first adds four buttons and then when one of the newly created buttons is clicked all the buttons are cleared.

Example

Private Sub RemoveButton(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
    If (sp1.Children.IndexOf(btn) >= 0) Or (sp1.Children.IndexOf(btn1) >= 0) Or (sp1.Children.IndexOf(btn2) >= 0) Or (sp1.Children.IndexOf(btn3) >= 0) Then
        sp1.Children.RemoveAt(0)
    End If 
End Sub
<TabItem MouseLeftButtonUp="ClearButtons">
<TabItem.Header>Clear Controls</TabItem.Header>
</TabItem>

...

        void ClearButtons(object sender, MouseButtonEventArgs e)
        {
            sp1.Children.Clear();
            btn = new Button();
            btn.Content = "Click to clear";
            sp1.Children.Add(btn);
            btn.Click += (ClearControls);
            btn1 = new Button();
            btn1.Content = "Click to clear";
            sp1.Children.Add(btn1);
            btn1.Click += (ClearControls);
            btn2 = new Button();
            btn2.Content = "Click to clear";
            sp1.Children.Add(btn2);
            btn2.Click += (ClearControls);
            btn3 = new Button();
            btn3.Content = "Click to clear";
            sp1.Children.Add(btn3);
            btn3.Click += (ClearControls);
        }

        void ClearControls(object sender, RoutedEventArgs e)
        {
            sp1.Children.Clear();
        }

The event handler may also be written in Microsoft Visual Basic .NET.

Private Sub ClearButtons(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
    sp1.Children.Clear()
    btn = New Button()
    btn.Content = "Click to clear"
    sp1.Children.Add(btn)
    AddHandler btn.Click, AddressOf Me.ClearControls
    btn1 = New Button()
    btn1.Content = "Click to clear"
    sp1.Children.Add(btn1)
    AddHandler btn1.Click, AddressOf Me.ClearControls
    btn2 = New Button()
    btn2.Content = "Click to clear"
    sp1.Children.Add(btn2)
    AddHandler btn2.Click, AddressOf Me.ClearControls
    btn3 = New Button()
    btn3.Content = "Click to clear"
    sp1.Children.Add(btn3)
    AddHandler btn3.Click, AddressOf Me.ClearControls
End Sub 

Private Sub ClearControls(ByVal sender As Object, ByVal e As RoutedEventArgs)
    sp1.Children.Clear()
End Sub
void ContainsElement(object sender, RoutedEventArgs e)
{
    TextBlock txt1 = new TextBlock();
    sp1.Children.Add(txt1);
    txt1.Text = "This StackPanel contains UIElement btn1: " + sp1.Children.Contains(btn1).ToString();
}

Note

For the complete code sample, see Using Elements Sample.

See Also

Tasks

Using Elements Sample

Reference

UIElementCollection