C# 如何在datagridviewcell上绘制自定义控件?

C# 如何在datagridviewcell上绘制自定义控件?,c#,winforms,datagridview,custom-controls,C#,Winforms,Datagridview,Custom Controls,我想为datagridviewcell托管一个自定义控件 我得到的唯一好的推荐信是 但是,我希望单元格在屏幕上显示我自己的usercontrol public class CustomCell : DataGridViewTextBoxCell { protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.

我想为
datagridviewcell
托管一个自定义控件

我得到的唯一好的推荐信是

但是,我希望单元格在屏幕上显示我自己的usercontrol

 public class CustomCell : DataGridViewTextBoxCell
 {   
     protected override void Paint(System.Drawing.Graphics graphics,
       System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds,
        int rowIndex, DataGridViewElementStates cellState, object value, object 
          formattedValue, string errorText, DataGridViewCellStyle cellStyle,
            DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
     {
          base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, 
            formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);               
     }
 }

有人能告诉我怎么做吗?

为了节省资源,
DataGridView
控件中的单元格大部分时间都在显示模式下,只有当用户使用鼠标或键盘进入单元格时才切换到编辑模式。您在问题中提到的示例被视为最佳实践,因为编辑控件(在这种情况下,
DateTimePicker
,但也可以很容易地成为您自己的自定义用户控件)仅在编辑模式下出现,因此一次仅对一个单元格显示

当单元格未处于编辑模式时,它应该使用
DataGridViewCell
子类的
Paint
方法中的逻辑来呈现其值的等效表示。您可以通过以下几种方式之一进行此操作:

  • 只需根据单元格的值在单元格的边界上绘制文本或图像;不要试图复制编辑控件的外观
  • 使用
    ControlPaint
    VisualStyleRenderer
    模拟编辑控件的外观(注意:这需要大量额外工作)
  • 将绘制代码从自定义用户控件移动到实用程序类中,以便它和单元格都可以使用相同的绘制代码

在大多数情况下,第一种选择就足够了;如果单元格的外观与编辑控件完全相同,则仅尝试其他方法之一。

如何在单元格上“绘制”用户控件以显示模式?@Melvin如果它是完全由用户绘制的控件,则可以运行控件的
绘制
方法中的相同代码。如果它是复合控件(使用其他控件),您可以将控件绘制到中间的
位图
(使用
DrawToBitmap
方法),然后将位图绘制到单元格上,否则您必须恢复到我介绍的第二种技术。