How can I remove a dynamically created button?
I want to remove all children of a StackPanel except for a Label, but I can't get it to 
remove a dynamically created Button.
<StackPanel Name="myStackPanel">
    <Label Name="myLabel">Label text</Label>
    <TextBlock Name="myTextBlock">TextBlock text</TextBlock>
</StackPanel>
private void button1_Click(object sender, RoutedEventArgs e)
    {
    Button buttonX= new Button();
    buttonX.Name = "ButtonInstall";
    buttonX.Content = "Click Me开发者_如何学运维";
    buttonX.Width = 150;
    buttonX.HorizontalAlignment = HorizontalAlignment.Left;
    buttonX.Click += new RoutedEventHandler(buttonX_Click); 
    myStackPanel.Children.Add(buttonX); 
    }
private void button2_Click(object sender, RoutedEventArgs e)
    {
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myStackPanel); i++)
        {
        Visual childVisual = (Visual)VisualTreeHelper.GetChild(myStackPanel, i);
        string controlName = childVisual.GetValue(Control.NameProperty).ToString();
        if (childVisual.GetType() != typeof(Label))
        {        
            myStackPanel.Children.Remove((UIElement)childVisual);
        }
    }
For your example, it's not necessary to use the VisualTreeHelper: 
List<UIElement> delItems=new List<UIElement>();
foreach(UIElement uiElement in myStackPanel.Children){
 if(uiElement is Label) continue;
 delItems.Add(uiElement);
}
foreach(UIElement delItem in delItems){
  myStackPanel.Children.Remove(delItem);
}
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论