我将DataGridViewCell和Column子类化为DataGridViewLabelCell
和DataGridViewLabelColumn
,这允许我添加要在单元格中显示的标签。我的想法是,我可以将标签堆叠在一起,使用不同的颜色,还可以处理各个标签上的点击事件。 DataGridViewLabelCell
具有以下代码来添加标签:
public void AddLabel(string LabelText, Color BackColor, int Opacity, float ScalePosition, object Tag)
{
Label label = new Label();
label.Visible = false;
label.Text = LabelText;
label.AutoSize = true;
label.BorderStyle = BorderStyle.Fixed3D;
label.BackColor = Color.FromArgb(Opacity, BackColor);
this.DataGridView.Controls.Add(label);
LabelScalePostion labelScale = new LabelScalePostion();
labelScale.Label = label;
labelScale.ScalePosition = ScalePosition;
label.DoubleClick += new EventHandler(DataGridViewCellLabel_DoubleClick);
_labels.Add(labelScale);
}
private void DataGridViewCellLabel_DoubleClick(object sender, EventArgs e)
{
Label label = (Label)sender;
MessageBox.Show("ID = " + label.Tag.ToString());
}
我还覆盖了DataGridViewLabelCell
的{{1}}事件来定位标签:
Paint
这是因为标签在包含它的单元格滚动到视图中之前不会显示,但是当它滚动到视图之外时,标签会停留在DGV的顶部。因此,当单元格停止显示时,我需要一些触发事件的方法,但是我找不到任何此类事件。
我目前正在使用拥有DataGridView的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);
foreach (LabelScalePostion labelScale in _labels)
{
Label label = labelScale.Label;
label.Visible = true;
Point location = cellBounds.Location;
location.Offset(40, (int)(cellBounds.Height * labelScale.ScalePosition));
label.Location = location;
}
}
事件处理此问题,如下所示:
Scroll
然而,这感觉不对,并且当我滚动时证明存在丑陋的闪烁。其他一切工作正常(外观,事件等),我可以忍受闪烁,但我敢肯定必须有一个更好的方法来实现这一点。