public partial class Window2 : Window
{
int margin = 200;
public Window2()
{
this.InitializeComponent();
for (int i = 1; i <= 5; i++)
{
TextBlock DynamicLine = new TextBlock();
DynamicLine.Name = "lbl_DynamicLine" + i;
DynamicLine.Width = 600;
DynamicLine.Height = 20;
DynamicLine.Text =i+"Dynamic TextBlock";
DynamicLine.Margin = new Thickness(50, margin, 0, 0);
margin = margin + 20;
LayoutRoot.Children.Add(DynamicLine);
}
}
}
我尝试动态删除文本块,如下所示。
LayoutRoot.Children.Remove(DynamicLine);
但是我可以仅使用上面的代码行删除最后创建的文本块。现在我想要动态删除所有文本块。我应该怎么做。
答案 0 :(得分:2)
试试这段代码
public partial class Window2 : Window
{
int margin = 200;
TextBlock DynamicLine;
public Window2()
{
this.InitializeComponent();
for (int i = 1; i <= 5; i++)
{
DynamicLine = new TextBlock();
DynamicLine.Name = "lbl_DynamicLine" + i;
RegisterName(DynamicLine.Name, DynamicLine);
DynamicLine.Width = 600;
DynamicLine.Height = 20;
DynamicLine.Text =i+"Dynamic TextBlock";
DynamicLine.Margin = new Thickness(50, margin, 0, 0);
margin = margin + 20;
LayoutRoot.Children.Add(DynamicLine);
}
for (int i = 1; i <= 5; i++)
{
DynamicLine = (TextBlock)this.FindName("lbl_DynamicLine" + i);
LayoutRoot.Children.Remove(DynamicLine);
}
}
}
答案 1 :(得分:1)
要删除所有子项,您应该调用clear方法。
LayoutRoot.Children.Clear();
答案 2 :(得分:0)
for (int i = LayoutRoot.Children.Count; i > 0; i--)
{
LayoutRoot.Children.RemoveAt(i-1);
}