0
我想删除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);
}
}
为什么不通过'Children'迭代如果添加呢?你需要为(int i = stackPanel.Children.Count - 1; i> 0; i--)做if(!(stackPanel.Children [i]是Label))stackPanel.Children.RemoveAt(i );' – Vlad
这就是为什么我们有MVVM和DataTemplates。 – Will
为什么不直接在button2.MouseDown触发器上为buttonX设置Visibility.Collapsed? –