C# 关于Grid下动态删除行列的操作

假设我们有以下布局

 "Grid" ShowGridLines="True">
        
            
            
            
            
            
        

        "One"
                   Grid.Row="0"
                   Text="1" />
        "Two"
                   Grid.Row="1"
                   Text="2" />
        "Three" 
                   Grid.Row="2"
                   Text="3" />
        "Four" 
                   Grid.Row="3"
                   Text="4" />
        "Five"
                   Grid.Row="4"
                   Text="5" />
    

展示出来的界面是这样子的

C# 关于Grid下动态删除行列的操作_第1张图片

我们尝试把2这一列删除~

Grid.Children.Remove(Two);

C# 关于Grid下动态删除行列的操作_第2张图片

删除是删除了,但第二列还是占了位置啊!

于是我们尝试以下操作

Grid.RowDefinitions.Remove()

这样的操作仅仅是删除了最后一行,5这个Textbox只能向上靠拢。

因此我们在删除之后,需要重新指定一下新位置

private void ReSetIndex(){
     var row = 0;
     foreach (var borderGridChild in BorderGrid.Children){
          (borderGridChild as UIElement)?.SetValue(Grid.RowProperty, row++);
     }
 }

C# 关于Grid下动态删除行列的操作_第3张图片

这样就正常了,但 Grid.RowDefinitions.Remove()这里怎么也得指定一下位置吧?

var row = Grid.RowDefinitions[int.Parse(Two.GetValue(Grid.RowProperty).ToString())];
private void Remove()
{
    var row = Grid.RowDefinitions[int.Parse(Two.GetValue(Grid.RowProperty).ToString())];
    Grid.Children.Remove(Two);
    Grid.RowDefinitions.Remove(row);
    ReSetIndex();
}
private void ReSetIndex()
{
    var row = 0;
    foreach (var borderGridChild in Grid.Children)
    {
        (borderGridChild as UIElement)?.SetValue(Grid.RowProperty, row++);
    }
}

 

转载于:https://www.cnblogs.com/yinghualuowu/p/9789491.html

你可能感兴趣的:(C# 关于Grid下动态删除行列的操作)