我在 WinForms 中有一個 Combobox,其中包含一組值。現在我將檢查組合框中選擇的值是否有效。完成后,如果該值無效,我需要以紅色顯示該值。怎么做?例如:考慮一個帶有元素{apple, mango, orange}的 ComboBox 。現在一個新元素被添加到串列中,比如Carrot。鑒于胡蘿卜是無效值,我想在 UI 中以紅色顯示值胡蘿卜。請讓我知道該怎么做。
提前致謝。
uj5u.com熱心網友回復:
將DrawMode組合框的屬性設定為OwnerDrawFixed
this.comboBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
定義組合框專案的自定義繪制方法
private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
var text = comboBox1.Items[e.Index] as string;
e.DrawBackground();
if (text == "orange")
{
TextRenderer.DrawText(e.Graphics,
text, e.Font, e.Bounds.Location, Color.Red);
}
else
{
TextRenderer.DrawText(e.Graphics,
text, e.Font, e.Bounds.Location, e.ForeColor);
}
}
將此方法訂閱到DrawItem您的組合框的事件
this.comboBox1.DrawItem =
new System.Windows.Forms.DrawItemEventHandler(this.ComboBox1_DrawItem);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489386.html
