2016-06-08 67 views
2

我的DataGridView上有一个DataGridViewComboBoxColumn。这是我的自定义单元格的绘画处理程序:自动调整使用自定义绘画的DataGridViewComboBoxCell

private void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) 
{ 
    if (e.ColumnIndex == 1 && e.RowIndex >= 0) 
    { 
     e.PaintBackground(e.CellBounds, true); 
     //e.PaintContent(e.CellBounds); 

     Graphics g = e.Graphics; 
     Color c = Color.Empty; 
     string s = ""; 
     Brush br = SystemBrushes.WindowText; 
     Brush brBack; 
     Rectangle rDraw; 

     rDraw = e.CellBounds; 
     rDraw = Rectangle.FromLTRB(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Right, e.CellBounds.Bottom - 1); 

     brBack = Brushes.White; 
     Pen penGridlines = new Pen(dataGridView.GridColor); 
     g.DrawRectangle(penGridlines, rDraw); 
     g.FillRectangle(brBack, rDraw); 
     penGridlines.Dispose(); 

     if (dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null) 
     { 
      ComboboxColourItem oColourItem = (ComboboxColourItem)dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; 
      s = oColourItem.ToString(); 
      c = oColourItem.Value; 
     } 

     int butSize = e.CellBounds.Height; 
     Rectangle rbut = new Rectangle(e.CellBounds.Right - butSize, 
             e.CellBounds.Top, butSize, butSize); 
     ComboBoxRenderer.DrawDropDownButton(e.Graphics, rbut, 
        System.Windows.Forms.VisualStyles.ComboBoxState.Normal); 


     if (c != Color.Empty) 
     { 
      SolidBrush b = new SolidBrush(c); 
      Rectangle r = new Rectangle(e.CellBounds.Left + 6, 
             e.CellBounds.Top + 5, 10, 10); 
      g.FillRectangle(b, r); 
      g.DrawRectangle(Pens.Black, r); 
      g.DrawString(s, Form.DefaultFont, Brushes.Black, 
         e.CellBounds.Left + 25, e.CellBounds.Top + 3); 

      b.Dispose(); 
     } 

     e.Handled = true; 
    } 
} 

当我去了,以自动调整我的填充柱双击DVG这个右边的编辑是发生了什么:

Autosize

我如何调整行为,以便在自动调整时考虑组合下拉菜单?

谢谢。

+0

那是油漆之外众所周知,下拉按钮的宽度事件? – DonBoitnott

+0

@DonBoitnott不,但宽度在paint事件中指定为'e.CellBounds.Height',所以也许我们有它? –

+0

我不使用DGV,所以我不知道可能有哪些事件可用,但我会查找(按顺序):直接覆盖列自动大小;调整大小后会发生的事情;或'ColumnWidthChanged'。您应该可以使用其中的一个来确定它是否是您关心的列,并为按钮添加更多宽度。 AutoSize永远不会知道它,所以你必须手工完成。 – DonBoitnott

回答

2

当您双击列标题分隔符以使列自动调整大小时,它将使列宽等于最宽的单元格。在自动调整大小模式的组合框单元的宽度是使用计算:

  • 格式化值的宽度
  • 组合框按钮
  • 细胞风格填充
  • 错误图标宽度
  • 一些额外的填充的宽度周围的文本和按钮和图标

快速修复

在你的情况下,当计算单元格的自动大小时,那些彩色矩形将占用空间,但它们的宽度和空间不会被计算。

作为一个简单的解决方案,您可以在列中添加一些填充。您可以在设计人员中编辑列,并在列中设置DefaultCellStyle的填充。还使用代码,你可以,例如写:

column.DefaultCellStyle.Padding = new Padding(16,0,16,0); 

长期的解决方案

如果列是可重复使用的列类型,我建议你创建自定义字段类型。然后,您可以封装绘画逻辑并计算您的自定义单元格中的大小和其他一些功能。如果你决定创建自定义单元格,你会发现相关问题有用的这些方法:

+0

谢谢!很棒。 –

+0

不客气:) –

+1

把'ComboBoxRenderer.DrawDropDownButton ...'在绘制结束时,按钮应该呈现在文本上方。目前正如你所见,文本是通过组合框按钮绘制的。绘制文本后,应绘制组合框按钮。 –