2012-12-26 63 views
3

我已经扩展了DataGridView单元格以显示其角落中的Tag属性中的文本(例如,在日历的角落中显示日期编号),并希望能够指定颜色和不透明度的文字。将属性添加到窗体控件

要完成此操作,我已将2个属性添加到子类DataGridView单元中,但它们在运行时不存储它们的值。这是DataGridViewCell的和列:

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中?

+0

不同于论坛的网站,我们不使用的“谢谢”,或者“任何帮助表示赞赏”,或签名[等等]。请参阅“[应该'嗨','谢谢',标语和致敬从帖子中删除?](http://meta.stackexchange.com/questions/2950/should-hi-thanks-taglines-and-salutations-be -removed-from-posts)。 –

+0

够公平的,会保持这种想法 – CrazyHorse

回答

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); 
相关问题