如何删除动态创建的按钮?

时间:2011-08-18 14:05:00

标签: c# wpf xaml

除了StackPanel之外,我想删除Label的所有子项,但我无法将其删除 删除动态创建的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);
        }
    }

1 个答案:

答案 0 :(得分:3)

对于您的示例,没有必要使用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);
}