gpt4 book ai didi

c# - 向表单控件添加属性

转载 作者:行者123 更新时间:2023-11-30 18:36:07 25 4
gpt4 key购买 nike

我已经扩展了 DataGridView 单元格以在角落显示其 Tag 属性中的文本(例如,在日历的角落显示天数)并且希望能够指定文本的颜色和不透明度。

为了实现这一点,我向子类化的 DataGridView 单元格添加了 2 个属性,但是它们不在运行时存储它们的值。这是 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 中?

最佳答案

我相信这是因为 CellTemplate 存储为更通用的 DataGridViewCell,而不是子类 LabelCell。无论如何,将值存储在 Column 上并从那里引用它们就可以了:

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

关于c# - 向表单控件添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14045456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com