Export (0) Print
Expand All

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.

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.

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();
}
NoteNote:

For the complete code sample, see Using Elements Sample.

Community Additions

ADD
Show:
© 2014 Microsoft