WPF Grid绘制网格线

private void DrawGrid(Grid grid)
{
    var color = ColorConverter.ConvertFromString("#B2586697");
    if (color == null) return;
    double myBorderWidth = 1;
    //根据Grid的顶层子控件的个数去添加边框,同时考虑合并的情况
    var controls = grid.Children;
    var count = controls.Count;
    for (int i = 0; i < count; i++)
    {
        var item = controls[i] as FrameworkElement;
        if (item == null) continue;

        var row = Grid.GetRow(item);
        var column = Grid.GetColumn(item);
        var rowspan = Grid.GetRowSpan(item);
        var columnspan = Grid.GetColumnSpan(item);
        //设置边框线的颜色
        var border = new Border { BorderBrush = new SolidColorBrush((Color)color) };

        if (row + rowspan == grid.RowDefinitions.Count && column + columnspan == grid.ColumnDefinitions.Count)
            border.BorderThickness = new Thickness(myBorderWidth);
        else if (row + rowspan == grid.RowDefinitions.Count)
            border.BorderThickness = new Thickness(myBorderWidth, myBorderWidth, 0, myBorderWidth);
        else if (column + columnspan == grid.ColumnDefinitions.Count)
            border.BorderThickness = new Thickness(myBorderWidth, myBorderWidth, myBorderWidth, 0);
        else
            border.BorderThickness = new Thickness(myBorderWidth, myBorderWidth, 0, 0);

        Grid.SetRow(border, row);
        Grid.SetColumn(border, column);
        Grid.SetRowSpan(border, rowspan);
        Grid.SetColumnSpan(border, columnspan);
        grid.Children.Add(border);
    }
}

你可能感兴趣的:(wpf)