如何在datagridviewcell上绘制自定义控件? [英] How to paint custom control on datagridviewcell?

查看:563
本文介绍了如何在datagridviewcell上绘制自定义控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 datagridviewcell 托管自定义控件。

I want to host a custom control for datagridviewcell.

唯一的好参考是 http://msdn.microsoft.com/en-us/library/7tas5c80.aspx

但是,我想让单元格显示我的自己的usercontrol代替

However, i want the cell to display my own usercontrol instead on

 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);               
     }
 }

任何人都可以指导我如何做? p>

Can anyone guide me how to do it ?

推荐答案

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

In order to save on resources, the cells in a DataGridView control spend most of their time in display mode, only changing to edit mode when the user enters the cell using the mouse or keyboard. The example you referred to in your question is regarded as best practice, because the editing control (in that case, a DateTimePicker, but could just as easily be your own custom user control) only ever appears in edit mode, and thus only for one cell at a time.

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

When the cell is not in edit mode, it should render an equivalent representation of its value using logic inside the Paint method of your subclass of DataGridViewCell. You could do this in one of several ways:


  • 只需将文本或图像基于其值来绘制到单元格的边界;不要尝试复制编辑控件的外观。

  • 使用 ControlPaint VisualStyleRenderer (注意:这涉及到很多额外的工作)。

  • 将绘图代码从自定义用户控件移动到实用程序类中,因此它和单元格可以使用相同的绘图代码。

  • Simply draw text or an image onto the bounds of the cell based on its value; don't try to replicate the way that the editing control looks.
  • Simulate the appearance of the editing control using ControlPaint or VisualStyleRenderer (note: this involves a lot of extra work).
  • Move the painting code from your custom user control into a utility class, so that both it and the cell can use the same painting code.

在大多数情况下,第一个选项将足够;只有尝试其他方法之一,如果重要的是单元格看起来与编辑控件完全相同。

In most cases, the first option will be sufficient; only attempt one of the other approaches if it is important for the cell to look EXACTLY the same as your editing control.

这篇关于如何在datagridviewcell上绘制自定义控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆