合并数据网格控件中的单元格

时间:2018-01-26 11:46:01

标签: c# wpf merge datagrid cell

我必须创建一个datagrid控件(不是datagridview,也不是grid也不是listview),它需要合并一些单元格,以防它们具有相同的值(只是一些单元格)。 datagrid的所有数据都必须用ItemsSource绑定填充,datagrid的结构将以编程方式定义,而不是在xaml中,以使其对其他类通用。

在其他帖子中:

ContentResolver.openInputStream(Uri)

表的结构(列)的定义是在xaml中定义的,但我需要它与itemsource或类似的东西是通用的。

1 个答案:

答案 0 :(得分:0)

DGV在合并“单元格”方面绝对不像Excel,我认为在这种情况下并没有很多东西,但你可以尝试这种方法。

private void MergeCellsInRow(int row, int col1, int col2)
{
    Graphics g = dataGridView1.CreateGraphics();
    Pen p = new Pen(dataGridView1.GridColor);
    Rectangle r1 = dataGridView1.GetCellDisplayRectangle(col1, row, true);
    Rectangle r2 = dataGridView1.GetCellDisplayRectangle(col2, row, true);

    int recWidth = 0;
    string recValue = string.Empty;
    for (int i = col1; i <= col2; i++)
    {
    recWidth += dataGridView1.GetCellDisplayRectangle(i, row, true).Width;
    if (dataGridView1[i, row].Value != null)
        recValue += dataGridView1[i, row].Value.ToString() + " ";
    }
    Rectangle newCell = new Rectangle(r1.X, r1.Y, recWidth, r1.Height);
    g.FillRectangle(new SolidBrush(dataGridView1.DefaultCellStyle.BackColor), newCell);
    g.DrawRectangle(p, newCell);
    g.DrawString(recValue, dataGridView1.DefaultCellStyle.Font, new SolidBrush(dataGridView1.DefaultCellStyle.ForeColor), newCell.X + 3, newCell.Y + 3);
}

private void MergeCellsInColumn(int col, int row1, int row2)
{
    Graphics g = dataGridView1.CreateGraphics();
    Pen p = new Pen(dataGridView1.GridColor);
    Rectangle r1 = dataGridView1.GetCellDisplayRectangle(col, row1, true);
    Rectangle r2 = dataGridView1.GetCellDisplayRectangle(col, row2, true);

    int recHeight = 0;
    string recValue = string.Empty;
    for (int i = row1; i <= row2; i++)
    {
    recHeight += dataGridView1.GetCellDisplayRectangle(col, i, true).Height;
    if (dataGridView1[col, i].Value != null)
        recValue += dataGridView1[col, i].Value.ToString() + " ";
    }
    Rectangle newCell = new Rectangle(r1.X, r1.Y, r1.Width, recHeight);
    g.FillRectangle(new SolidBrush(dataGridView1.DefaultCellStyle.BackColor), newCell);
    g.DrawRectangle(p, newCell);
    g.DrawString(recValue, dataGridView1.DefaultCellStyle.Font, new SolidBrush(dataGridView1.DefaultCellStyle.ForeColor), newCell.X + 3, newCell.Y + 3);
}