我有一个用户控件,代码如下:
public partial class ColorComboBox : ComboBox
{
public ColorComboBox()
{
InitializeComponent();
this.DropDownStyle = ComboBoxStyle.DropDownList;
this.DrawMode = DrawMode.OwnerDrawFixed;
string[] colorNames = System.Enum.GetNames( typeof( KnownColor ) );
this.Items.AddRange( colorNames );
}
protected override void OnDrawItem( DrawItemEventArgs e )
{
if ( e.Index < 0 ) return;
this.SuspendLayout();
string s = (string)this.Items[ e.Index ];
using ( Brush b = new SolidBrush( Color.FromName( s ) ) )
{
e.Graphics.DrawRectangle( Pens.Black, 2, e.Bounds.Top + 1, 20, 11 );
e.Graphics.FillRectangle( b, 3, e.Bounds.Top + 2, 19, 10 );
e.Graphics.DrawString( s, this.Font, Brushes.Black, 25, e.Bounds.Top );
}
e.DrawFocusRectangle();
this.ResumeLayout();
}
}
将此ComboBox的实例添加到表单后,我遇到了一个奇怪的问题;鼠标指针下的每个项目都将条目更改为粗体。
有谁知道为什么会这样?
感谢。
答案 0 :(得分:1)
我设法通过添加以下行来解决这个问题:
e.DrawBackground();
答案 1 :(得分:0)
谢谢它的工作正常
使用它:
label1.Text = colorComboBox1.SelectedItem.ToString();
label1.BackColor = Color.FromName(colorComboBox1.SelectedItem.ToString());
或
string s = (string)colorComboBox1.Items[colorComboBox1.SelectedIndex];
label1.Text = s;
label1.BackColor = Color.FromName(s);