如何更改ComboBox的选定项目的ForeColor?
是否可以更改所选(不是下拉!)项目的外观?
combobox.ForeColor仅将所有项目的文本颜色更改为下拉列表。
编辑:变种是beelow,我们是
public static void CBoxDrawItem(object sender, DrawItemEventArgs args) { var box = sender as ComboBox; if (box == null || args.Index = box.Items.Count) return; e.DrawBackground(); var data = box.Tag as ControlData; var color = (args.State & DrawItemState.ComboBoxEdit) == 0 || data == null || !data.IsInDefaultState ? e.ForeColor : GetDefaultColor(e.ForeColor); using (var brush = new SolidBrush(color)) { args.Graphics.DrawString(box.Items[args.Index].ToString(), args.Font, brush, args.Bounds.X, args.Bounds.Y); } args.DrawFocusRectangle(); }
您不必将FlatStyle
更改为Popup或Flat以使其工作。 而且你可能首先不想这样做,因为与应用程序界面的其他部分相比,这些样式看起来非常难看。 原生Windows控件使用3D风格的外观; Flat和Popup样式专为Web或Windows Mobile应用程序而设计,它们更适合。
我假设你问的是这个问题,因为你已经编写了代码来改变combobox中显示的文本的前景色,但是注意到它在Windows Vista或更高版本下无效。 这是因为当combobox的DropDownList
样式在这些版本的Windows中看起来更像是一个按钮时,它也失去了对自定义文本颜色的支持。 相反,所选文本始终以标准“窗口文本”颜色显示。 将DropDownList
样式与常规DropDown
样式combobox进行比较:
在视觉上,两个combobox在早期版本的Windows中看起来相同,但在Vista及更高版本下则不然。 获取自定义前景色的关键是将combobox控件的DropDownStyle
属性更改为DropDown
(实际上是默认值)。
我还想将FlatStyle
属性设置为System
以便您获得本机Windows控件提供的所有漂亮的淡入和淡出效果。 Standard
样式尝试在托管代码中模拟这些效果,但它没有完全正确的感觉。 我关心的是小事。
然后您可以使用以下代码(如Adrian的答案中最初建议的那样):
public Form1() { InitializeComponent(); // Set custom combobox styles comboBox1.DropDownStyle = ComboBoxStyle.DropDown; comboBox1.FlatStyle = FlatStyle.System; // Attach relevant event handler methods comboBox1.DropDown += new EventHandler(comboBox1_DropDown); comboBox1.DropDownClosed += new EventHandler(comboBox1_DropDownClosed); } void comboBox1_DropDown(object sender, EventArgs e) { // Optionally, revert the color back to the default // when the combobox is dropped-down // // (Note that we're using the ACTUAL default color here, // rather than hard-coding black) comboBox1.ForeColor = SystemColors.WindowText; } void comboBox1_DropDownClosed(object sender, EventArgs e) { // Change the color of the selected text in the combobox // to your custom color comboBox1.ForeColor = Color.Red; }
产生以下效果:
如果您可以将combobox的FlatStyle更改为Popup或Flat,则更改ForeColor时所选项目的颜色也会更改。
要仅更改所选项目的颜色,您可以实现某种解决方法,并在每次打开或关闭DropDown时更改ForeColor。
代码示例:
public Form1() { InitializeComponent(); comboBox1.FlatStyle = FlatStyle.Popup; comboBox1.DropDown += new EventHandler(comboBox1_DropDown); comboBox1.DropDownClosed += new EventHandler(comboBox1_DropDownClosed); } void comboBox1_DropDownClosed(object sender, EventArgs e) { comboBox1.ForeColor = Color.Red; } void comboBox1_DropDown(object sender, EventArgs e) { comboBox1.ForeColor = Color.Black; }
你可以使用Cody Gray’sugestion并将其添加到具有相同的DropDownList Style行为:
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = true; }
通过这种方式,用户无法编辑combobox。