0

我有一个 DataGridViewCell 和 Column 的子类DataGridViewLabelCellDataGridViewLabelColumn它允许我添加要在单元格中显示的标签。这个想法是我可以将标签堆叠在一起,使用不同的颜色,还可以处理单个标签上的点击事件。具有以下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'Paint事件来定位标签:

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

这在某种意义上是有效的,直到包含它的单元格滚动到视图中,标签才会显示,但是当它滚动回视图之外时,标签会停留在 DGV 的顶部。因此,当单元格停止显示时,我需要某种方式来触发事件,但是我找不到任何此类事件。

我目前正在使用拥有 DataGridView 的Scroll事件处理此问题,如下所示:

private void dgvItemView_Scroll(object sender, ScrollEventArgs e)
{
    switch (_formType)
    {
        case FormType.DayView:
            foreach (DataGridViewRow row in this.dgvItemView.Rows)
            {
                DataGridViewLabelCell cell = (DataGridViewLabelCell)row.Cells[0];

                foreach (DataGridViewLabelCell.LabelScalePostion labelScale in cell.Labels)
                    labelScale.Label.Visible = false;
            }
            break;
    }
}

但是,这感觉不对,并且为了证明这一点,当我滚动时会出现难看的闪烁。其他一切都很好(外观,事件等),我可以忍受闪烁,但是我确信必须有更好的方法来实现这一点。

4

0 回答 0