【发布时间】:2012-12-26 19:47:08
【问题描述】:
我已扩展 DataGridView 单元格以在角落显示其 Tag 属性中的文本(例如,在日历的角落显示天数)并希望能够指定文本的颜色和不透明度。
为了实现这一点,我向子类 DataGridView 单元格添加了 2 个属性,但是它们不会在运行时存储它们的值。这是 DataGridViewCell 和 Column:
class DataGridViewLabelCell : DataGridViewTextBoxCell
{
private Color _textColor;
private int _opacity;
public Color TextColor { get { return _textColor; } set { _textColor = value; } }
public int Opacity { get { return _opacity; } set { _opacity = value; } }
protected override void Paint(Graphics graphics,
Rectangle clipBounds,
Rectangle cellBounds,
int rowIndex,
DataGridViewElementStates cellState,
object value,
object formattedValue,
string errorText,
DataGridViewCellStyle cellStyle,
DataGridViewAdvancedBorderStyle advancedBorderStyle,
DataGridViewPaintParts paintParts)
{
// Call the base class method to paint the default cell appearance.
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
value, formattedValue, errorText, cellStyle,
advancedBorderStyle, paintParts);
if (base.Tag != null)
{
string tag = base.Tag.ToString();
Point point = new Point(base.ContentBounds.Location.X, base.ContentBounds.Location.Y);
Font font = new Font("Arial", 25.0F, FontStyle.Bold);
graphics.DrawString(tag, font, new SolidBrush(Color.FromArgb(_opacity, _textColor)), cellBounds.X, cellBounds.Y);
}
}
}
public class DataGridViewLabelCellColumn : DataGridViewColumn
{
public DataGridViewLabelCellColumn(Color TextColor, int Opacity = 128)
{
DataGridViewLabelCell template = new DataGridViewLabelCell();
template.TextColor = TextColor;
template.Opacity = Opacity;
this.CellTemplate = template;
}
}
我按如下方式添加列:
col = new DataGridViewLabelCellColumn(Color.Blue, 115);
dgv.Columns.Add(col);
col.HeaderText = "Saturday";
col.Name = "Saturday";
但是,如果我向 graphics.DrawString 行添加断点,_textColor 和 _opacity 都没有值。如果我为它们分配默认值如下:
private Color _textColor = Color.Red;
private int _opacity = 128;
然后它工作正常。如何确保值存储在 CellTemplate 中?
【问题讨论】:
-
与论坛网站不同,我们不使用“谢谢”、“任何帮助表示赞赏”或Stack Overflow 上的签名。请参阅“Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?.
-
公平,会记住这一点
标签: c# winforms datagridview