C# 使用组合框绘制项目事件
我正在使用ComboBox DrawItem事件,但当我使用此事件时,所选项目不起作用 我的意思是,我右键单击组合框中的某个特定项目,但在组合框中的选定行上随机显示一些其他项目(虽然选定的实际项目很好,但它仅显示选定了一些其他项目) 这是我的代码:C# 使用组合框绘制项目事件,c#,winforms,C#,Winforms,我正在使用ComboBox DrawItem事件,但当我使用此事件时,所选项目不起作用 我的意思是,我右键单击组合框中的某个特定项目,但在组合框中的选定行上随机显示一些其他项目(虽然选定的实际项目很好,但它仅显示选定了一些其他项目) 这是我的代码: System.Windows.Forms.ComboBox comboBox; comboBox = new System.Windows.Forms.ComboBox(); comboBox.AllowDrop = true; comboBox.D
System.Windows.Forms.ComboBox comboBox;
comboBox = new System.Windows.Forms.ComboBox();
comboBox.AllowDrop = true;
comboBox.DrawMode = DrawMode.OwnerDrawFixed;
comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
comboBox.FormattingEnabled = true;
comboBox.DrawItem += (sender, DrawItemEventArgs) =>
{
Font font = comboBox.Font;
Brush backgroundColor;
Brush textColor;
if (indexes.Contains(DrawItemEventArgs.Index))
{
if ((DrawItemEventArgs.State & DrawItemState.Selected)==DrawItemState.Selected)
{
backgroundColor = Brushes.Cyan;
textColor = Brushes.Black;
}
else
{
backgroundColor = Brushes.Brown;
textColor = Brushes.Black;
}
}
else
{
if ((DrawItemEventArgs.State & DrawItemState.Selected)==DrawItemState.Selected)
{
backgroundColor = SystemBrushes.Highlight;
textColor = SystemBrushes.HighlightText;
}
else
{
backgroundColor = SystemBrushes.Window;
textColor = SystemBrushes.WindowText;
}
}
DrawItemEventArgs.Graphics.FillRectangle(backgroundColor, DrawItemEventArgs.Bounds);
if (DrawItemEventArgs.Index == -1) return;
DrawItemEventArgs.Graphics.DrawString((sender as ComboBox).
Items[DrawItemEventArgs.Index].ToString(), font,textColor,DrawItemEventArgs.Bounds);
};
我的油漆有问题吗?因为我调试过,发现这个事件正在制造麻烦
tnx.抱歉,索引包含我想在组合框@Ganesh_DevlekarI中着色的特定索引。我认为您没有正确地将变量传递给lambda表达式。它不应该是这样的:
comboBox.DrawItem+=(sender,e)
并且在正文中使用DrawItemEventArgs时使用“e”吗?您的代码工作得很好。正确的项目被粉刷,我看不出选择了错误的项目。选择事件中是否有代码?你把你给我们看的代码放在哪里了?@o_weisman我再也不能撤消upvote了,但是lambda表达式很好,只要发送者不是重复的。然而,我确实会调用参数e以与正常命名方案保持一致。由于此错误,它失败了:e不包含“selected”的定义。