如何删除动态创建的按钮
本文关键字:动态 创建 按钮 删除 何删除 | 更新日期: 2023-09-27 18:06:05
我想删除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);
}
}
对于您的示例,没有必要使用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);
}