以 3d 样式显示 DataGridViewComboBoxColumn

Show DataGridViewComboBoxColumn in 3d Style

我正计划使 DataGridViewComboboxCell 的显示类似于文本框的 3D 固定样式。我设法使用此代码通过组合框完成此操作:

    public Form1()
    {
        cmbbox.DrawMode = DrawMode.OwnerDrawFixed;
        cmbbox.DrawItem += ComboBox_DrawItem_3DFixed;
    }

    private void ComboBox_DrawItem_3DFixed(object sender, DrawItemEventArgs e)
    {
        ComboBox cmb = sender as ComboBox;

        e.DrawBackground();
        if (e.State == DrawItemState.Focus)
            e.DrawFocusRectangle();

        var index = e.Index;
        if (index < 0 || index >= cmb.Items.Count)
            return;

        var item = cmb.Items[index];
        string text = (item == null) ? "(null)" : cmb.GetItemText(item);
        using (var brush = new SolidBrush(e.ForeColor))
        {
            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            e.Graphics.DrawString(text, e.Font, brush, e.Bounds);
        }
    }

不幸的是,我不知道如何使用 DataGridViewComboboxCell 来完成它。不过我确实在这里找到了解决方案:

    public void Form1()
    {
        dgView.CellPainting += dgView_EditingControlShowing;
    }

    void dgView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (e.Control is ComboBox)
        {
            ComboBox cb = (ComboBox)e.Control;
            cb.DrawMode = DrawMode.OwnerDrawFixed;
            cb.DrawItem += new DrawItemEventHandler(ComboBox_DrawItem_3DFixed);
        }
    }

但问题在于,它只会在单击特定单元格时更改 DataGridViewComboboxCell 的外观,而当它失去焦点时,它 returns 恢复正常。

我确实找到了 CellPainting 事件,但我不知道这段代码是如何工作的。谁能帮我?谢谢!

要创建 3D 样式 DataGridViewComboBoxColumn 您应该执行以下 2 个设置:

  1. 您应该禁用组合框编辑控件的视觉样式
  2. 你应该自己画组合框单元格并画一个 3d 组合按钮

为此,处理 EditingControlShowingCellPaint 事件:

[DllImport("uxtheme.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
static extern int SetWindowTheme(IntPtr hWnd, String pszSubAppName, String pszSubIdList);
void dataGridView1_EditingControlShowing(object sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is ComboBox)
        SetWindowTheme(e.Control.Handle, "", "");
}
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex >= 0 && e.RowIndex >= 0 &&
        this.dataGridView1.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn)
    {
        var r1 = e.CellBounds;
        using (var brush = new SolidBrush(e.CellStyle.BackColor))
            e.Graphics.FillRectangle(brush, r1);
        r1.Width --;
        ControlPaint.DrawBorder3D(e.Graphics, r1, Border3DStyle.Sunken);
        e.Paint(r1, DataGridViewPaintParts.Border |
            DataGridViewPaintParts.ContentForeground);
        var d = SystemInformation.VerticalScrollBarWidth;
        var r2 = new Rectangle(r1.Right - d - 2, r1.Top + 2, d, r1.Height - 5);
        ControlPaint.DrawComboButton(e.Graphics, r2, ButtonState.Normal);
        e.Handled = true;
    }
}

还要创建下面的外观,无需任何自定义代码,只需将您的列的 DisplayStyle 设置为 ComboBox: