gpt4 book ai didi

c# - ComboBoxCell 中的自定义绘制项

转载 作者:太空宇宙 更新时间:2023-11-03 13:31:47 24 4
gpt4 key购买 nike

我正在尝试使用 DrawItem 事件在 DataGridView 的 ComboBoxCell 中绘制项目。以下是我的代码。

更新代码:

private void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
int index = dgv.CurrentCell.ColumnIndex;
if (index == FormatColumnIndex)
{
var combobox = e.Control as ComboBox;
if (combobox == null)
return;
combobox.DrawMode = DrawMode.OwnerDrawFixed;
combobox.DrawItem -= combobox_DrawItem;
combobox.DrawItem += new DrawItemEventHandler(combobox_DrawItem);
}
}

void combobox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0)
{
return;
}
int index = dgv.CurrentCell.RowIndex;
if (index == e.Index)
{
DataGridViewComboBoxCell cmbcell = (DataGridViewComboBoxCell)dgv.CurrentRow.Cells["ProductFormat"];

string productID = dgv.Rows[cmbcell.RowIndex].Cells["ProductID"].Value.ToString();

string item = cmbcell.Items[e.Index].ToString();
if (item != null)
{
Font font = new System.Drawing.Font(FontFamily.GenericSansSerif, 8);
Brush backgroundColor;
Brush textColor;

if (e.State == DrawItemState.Selected)
{
backgroundColor = SystemBrushes.Highlight;
textColor = SystemBrushes.HighlightText;
}
else
{
backgroundColor = SystemBrushes.Window;
textColor = SystemBrushes.WindowText;
}
if (item == "Preferred" || item == "Other")
{
font = new Font(font, FontStyle.Bold);
backgroundColor = SystemBrushes.Window;
textColor = SystemBrushes.WindowText;
}


if (item != "Select" && item != "Preferred" && item != "Other")
e.Graphics.DrawString(item, font, textColor, new Rectangle(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height));
else
e.Graphics.DrawString(item, font, textColor, e.Bounds);
}
}
}
}

项目显示正确,但下拉菜单似乎不合适,看起来很别扭。

此外,当我将鼠标悬停在下拉项上时,它们似乎又被重新绘制了一遍,这使它们看起来更暗、更模糊。我怎样才能解决这个问题?谢谢。

最佳答案

您的绘图例程看起来像是将网格的 RowIndex 与 ComboBox 项目集合的 e.Index 混淆了。不同的东西。

尝试删除这个:

// int index = dgv.CurrentCell.RowIndex;
// if (index == e.Index) {

就模糊而言,添加以下行来修复:

void combobox_DrawItem(object sender, DrawItemEventArgs e) {
e.DrawBackground();

关于c# - ComboBoxCell 中的自定义绘制项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20244478/

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