Lon*_*kli 5 c# combobox .net-4.0 winforms
是否可以更改所选(不是下拉!)项目的外观?
combobox.ForeColor仅将所有项目的文本颜色更改为下拉列表.
编辑: 变种是beelow,我们是
public static void CBoxDrawItem(object sender, DrawItemEventArgs args)
{
var box = sender as ComboBox;
if (box == null || args.Index < 0 || 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();
}
Run Code Online (Sandbox Code Playgroud)
您不必将其更改FlatStyle为Popup或Flat以使其工作.而且你可能不想在第一时间那样做,因为与应用程序界面的其他部分相比,这些样式看起来非常难看.原生Windows控件使用3D风格的外观; Flat和Popup样式专为Web或Windows Mobile应用程序而设计,它们更适合.
我假设你问的是这个问题,因为你已经编写了代码来改变组合框中显示的文本的前景色,但是注意到它在Windows Vista或更高版本下无法正常工作.那是因为当DropDownList组合框的样式在这些版本的Windows中看起来更像是一个按钮时,它也失去了对自定义文本颜色的支持.相反,所选文本始终以标准"窗口文本"颜色显示.将DropDownList样式与常规DropDown样式组合框进行比较:

在视觉上,两个组合框在早期版本的Windows中看起来相同,但不是在Vista及更高版本下.获取自定义前景色的关键是将组合框控件的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;
}
Run Code Online (Sandbox Code Playgroud)
产生以下效果:

如果您可以将组合框的 FlatStyle 更改为 Popup 或 Flat,则当您更改 ForeColor 时,所选项目的颜色也会更改。

要仅更改所选项目的颜色,您可以实施某种解决方法,并在每次打开或关闭 DropDown 时更改前景色。
代码示例:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35709 次 |
| 最近记录: |