下面这段代码扩展了DataGridViewTextBoxColumn 和DataGridViewTextBoxCell类,将一个图片显示在文本旁边。这个示例使用了DataGridViewCellStyle.Padding 属性来调整文本的位置,重写了Paint 方法来绘制图片。该示例可以得到简化,方法是处理CellPainting 事件,在这里实现类的功能。
public class TextAndImageColumn:DataGridViewTextBoxColumn
{
private Image imageValue;
private Size imageSize;
public TextAndImageColumn()
{
this.CellTemplate = new TextAndImageCell();
}
public override object Clone()
{
TextAndImageColumn c = base.Clone() as TextAndImageColumn;
c.imageValue = this.imageValue;
c.imageSize = this.imageSize;
return c;
}
public Image Image
{
get { return this.imageValue; }
set
{
if (this.Image != value) {
this.imageValue = value;
this.imageSize = value.Size;
if (this.InheritedStyle != null) {
Padding inheritedPadding = this.InheritedStyle.Padding;
this.DefaultCellStyle.Padding = new Padding(imageSize.Width,
inheritedPadding.Top, inheritedPadding.Right,
inheritedPadding.Bottom);
}
}
}
}
private TextAndImageCell TextAndImageCellTemplate
{
get { return this.CellTemplate as TextAndImageCell; }
}
internal Size ImageSize
{
get { return imageSize; }
}
}
public class TextAndImageCell : DataGridViewTextBoxCell
{
private Image imageValue;
private Size imageSize;
public override object Clone()
{
TextAndImageCell c = base.Clone() as TextAndImageCell;
c.imageValue= this.imageValue;
c.imageSize = this.imageSize;
return c;
}
public Image Image
{
get {
if (this.OwningColumn == null ||
this.OwningTextAndImageColumn == null) {
return imageValue;
}
else if (this.imageValue != null) {
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/tongxinshuyu/article-50070-46.html
还讲陆军
备好导弹时刻准备着