[C#]WinForm 變換ComboBox下拉項目顏色

  • 13475
  • 0
  • 2011-07-11

[C#]WinForm 變換ComboBox下拉項目顏色

設定ComboBox.DrawMode 即可觸發ComboBox 的DrawItem事件

DrawMode是列舉值有三種模式:

  • Normal (預設值)
  • OwnerDrawFixed
    • 手動繪製項目,項目高度與寬度都相同
  • OwnerDrawnVariable
    • 手動繪製項目,項目高度與寬度可觸發MeasureItem事件定義

 

 

public void Form_Load()
{
	ComboBox.DrawMode = DrawMode.OwnerDrawFixed;
}

private void ComboBoxDropDown_DrawItem(object sender, DrawItemEventArgs e)
{
	ComboBox cBox = (ComboBox)sender;
	e.DrawBackground();
	 foreach (var item in cBox .Items)
	{
		e.Graphics.DrawString(item.DisplayName, e.Font, new SolidBrush(Color.Gray), (Rectangle)e.Bounds);
		e.DrawFocusRectangle();
	}
}

 

image

 

 

選擇項目後,控制項欄位也要跟著變顏色

private void ComboBoxDropDownClosed(object sender, EventArgs e)
{
	ComboBox cb = (ComboBox)sender;
	Object  selectItem = cb.SelectedItem as Object  ;
	foreach (Object  item in cb .Items)
	{
		if (selectItem == item)
		{
			pComboBox.ForeColor = Color.Gray;
		}
		else
		{
			pComboBox.ForeColor = Color.Black;
		}
	}
}

image

新手發文請多多指教 ^_____^