删除WPF网格中的最后一行

时间:2013-08-28 17:09:10

标签: wpf grid row controls

我想删除网格的最后一行。我希望最后一行删除其中包含'2'的行。但是,无论我是删除第0行还是第1行,都会删除第0行。我怀疑我错过了关于行与网格的微妙之处。我做错了什么:

        // Create row 0
        RowDefinition row = new RowDefinition();
        row.Height = GridLength.Auto;
        myGrid.RowDefinitions.Add(row);

        // Add someting to it
        TextBox tb = new TextBox();
        tb.Text = "1";
        Grid.SetColumn(tb, 0);
        Grid.SetRow(tb, 0);
        myGrid.Children.Add(tb);

        // create row 1
        row = new RowDefinition();
        row.Height = GridLength.Auto;
        myGrid.RowDefinitions.Add(row);

        // Add something to it
        tb = new TextBox();
        tb.Text = "2";
        Grid.SetColumn(tb, 0);
        Grid.SetRow(tb, 1);
        myGrid.Children.Add(tb);

        // Delete row 1 (second row 0-indexed) <<< only row 0 is deleted
        myGrid.RowDefinitions.RemoveAt(1);

注意:我也尝试过:

        myGrid.RowDefinitions.Remove(myGrid.RowDefinitions[1]);

同样的结果。感谢您的任何见解。

1 个答案:

答案 0 :(得分:0)

当您从网格中删除一行时,它不会删除该行上的子项,您必须自己执行此操作。您可以尝试迭代网格的子项并删除行值等于要删除的行的所有元素...

var rowToDelete = 3;
foreach (var element in myGrid.Children)
{
    if(Grid.GetRow(element) == rowToDelete)
    {
        myGrid.Children.Remove(element);
    }
}