2
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);

但我只能使用上面的代码行删除最后创建的文本块。现在我想动态删除所有文本块。我该怎么做。

4

3 回答 3

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

    }
}
于 2012-07-20T11:42:55.307 回答
1

要删除所有子项,您应该调用 clear 方法。

LayoutRoot.Children.Clear();
于 2012-07-20T10:46:57.250 回答
0
for (int i = LayoutRoot.Children.Count; i > 0; i--)
{
    LayoutRoot.Children.RemoveAt(i-1);
}
于 2012-07-20T10:45:43.387 回答