假設我們有以下布局
<Grid x:Name="Grid" ShowGridLines="True"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition /> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <TextBlock x:Name="One" Grid.Row="0" Text="1" /> <TextBlock x:Name="Two" Grid.Row="1" Text="2" /> <TextBlock x:Name="Three" Grid.Row="2" Text="3" /> <TextBlock x:Name="Four" Grid.Row="3" Text="4" /> <TextBlock x:Name="Five" Grid.Row="4" Text="5" /> </Grid>
展示出來的界面是這樣子的
我們嘗試把2這一列刪除~
Grid.Children.Remove(Two);
刪除是刪除了,但第二列還是占了位置啊!
於是我們嘗試以下操作
Grid.RowDefinitions.Remove()
這樣的操作僅僅是刪除了最后一行,5這個Textbox只能向上靠攏。
因此我們在刪除之后,需要重新指定一下新位置
private void ReSetIndex(){ var row = 0; foreach (var borderGridChild in BorderGrid.Children){ (borderGridChild as UIElement)?.SetValue(Grid.RowProperty, row++); } }
這樣就正常了,但 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++); } }