可以在RowDefinition删除时自动重新调整Grid.Row吗?

时间:2012-09-25 16:57:08

标签: c# wpf grid

我正在以编程方式操作WPF Grid。我有一个动态添加RowDefinition的按钮,我的一个网格列包含一个按钮,用于删除网格中的任何RowDefinition。

当我点击“删除”按钮时,我执行:

//Logic to remove all Cell contents first fort this Row
// ...
//Then Remove my RowDefinition
myGrid.RowDefinitions.Remove(MyRowDefinition);

这很好用,我遇到的问题是其余控件的Grid.Row AttachedProperty没有自动重新调整。

有没有办法实现这个目标?

所以如果我有:

<Label Name="lbl1" Grid.Row="0"/>
<Label Name="lbl2" Grid.Row="1"/>
<Label Name="lbl3" Grid.Row="2"/>

我删除了我希望最终得到的第二个RowDefinition:

    <Label Name="lbl1" Grid.Row="0"/>
    <Label Name="lbl3" Grid.Row="1"/>

不是我得到的东西:

    <Label Name="lbl1" Grid.Row="0"/>
    <Label Name="lbl3" Grid.Row="2"/>

但事实并非如此。如果没有自动方法,那么我将不得不自己编写代码。

请告知..

以下是我的应用的样子: FormDesigner

2 个答案:

答案 0 :(得分:2)

您需要添加代码来自行处理。除非您不使用网格,并且使用ListBox,其ListBoxItem模板是一个包含3列和一行的网格。一列是红色拖动区域,另一列是蓝色拖动区域,第三列是按钮。您只需要一行,因为每个ListBox项目现在将代表一个网格行。

您要做的第一件事是确保在上面显示的网格中存储数据的集合是一个ObservableCollection。然后将其绑定到ListBox的ItemsSource。我不确定您的数据是什么样的,所以如果您有任何绑定,请确保正确处理所有绑定。

为按钮的PreviewMouseUp添加处理程序。使用PreviewMouseUp允许ListBox在处理按钮的PreviewMouseUp之前更改SelectedItem。然后,让相应的处理程序从绑定到ListBox的集合中删除ListBox.SelectedItem。

因为,要更改的集合是绑定到ItemsSource的ObservableCollection,将通知ListBox更新其绑定并将为您处理所有删除。

答案 1 :(得分:0)

以下是我手动解决的问题:

            myGrid.RowDefinitions.Remove(MyRowDefinition);
            myGrid.ReadjustRows(RemovedRowIndex);

我创建了几个扩展方法:

    public static  List<UIElement> GetGridCellChildren(this Grid grid, int row, int col)
    {
        return grid.Children.Cast<UIElement>().Where(
                            x => Grid.GetRow(x) == row && Grid.GetColumn(x) == col).ToList();
    }

    public static void ReadjustRows(this Grid myGrid, int row)
    {
        if (row < myGrid.RowDefinitions.Count)
        {
            for (int i = row + 1; i <= myGrid.RowDefinitions.Count; i++)
            {
                for (int j = 0; j < myGrid.ColumnDefinitions.Count; j++)
                {
                    List<UIElement> children = myGrid.GetGridCellChildren(i, j);
                    foreach(UIElement uie in children)
                    {
                        Grid.SetRow(uie,i - 1);
                    }
                }
            }
        }
    }

如果有人需要它,这里我的扩展方法是删除给定网格单元格的所有内容:

    public static void RemoveGridCellChildren(this Grid grid, int row, int col)
    {
        List<UIElement> GridCellChildren = GetGridCellChildren(grid, row, col);
        if (GridCellChildren != null && GridCellChildren.Count > 0)
        {
            foreach (UIElement uie in GridCellChildren)
            {
                grid.Children.Remove(uie);
            }
        }
    }