开发者

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜