向表单控件添加属性

3
我已经扩展了DataGridView单元格,使其在角落中显示来自其Tag属性的文本(例如,在日历的角落中显示日期数字),我希望能够指定文本的颜色和透明度。
为实现此目的,我已将两个属性添加到子类化的DataGridView单元格中,但它们在运行时没有存储它们的值。这是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中?


与论坛网站不同,我们在[so]上不使用“谢谢”、“任何帮助都会感激”或签名。请参阅“是否应该从帖子中删除‘Hi’、‘thanks’、标语和称呼? - John Saunders
好的,我会记住的。 - Niall
1个回答

0

我认为这是因为CellTemplate被存储为更通用的DataGridViewCell,而不是子类化的LabelCell。无论如何,在列上存储值并从那里引用它们就可以正常工作:

DataGridViewLabelCellColumn clm = (DataGridViewLabelCellColumn)base.OwningColumn;
int opacity = clm.Opacity;
Color textColor = clm.TextColor;
graphics.DrawString(tag, font, new SolidBrush(Color.FromArgb(opacity, textColor)), cellBounds.X, cellBounds.Y);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接