c# - 如何更改 ComboBox 的选定项的 ForeColor?

标签 c# winforms .net-4.0 combobox

是否可以更改所选(不在下拉列表中!)项目的外观?

combobox.ForeColor 仅将所有项目的文本颜色更改为下拉列表。

编辑: 下面是变体,我们的是

 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();
    }

最佳答案

您不必将 FlatStyle 更改为 Popup 或 Flat 即可完成这项工作。而且您可能一开始就不想这样做,因为与应用程序界面的其余部分相比,这些样式往往看起来非常难看。 native Windows 控件使用 3D 样式的外观; Flat 和 Popup 样式是为 Web 或 Windows Mobile 应用程序设计的,它们更适合这些应用程序。

我假设您问这个问题是因为您已经编写了代码来更改组合框中显示的文本的前景色,但注意到它在 Windows Vista 或更高版本下不起作用。这是因为当组合框的 DropDownList 样式在那些版本的 Windows 中变得更像一个按钮时,它也失去了对自定义文本颜色的支持。相反,所选文本始终以标准“窗口文本”颜色显示。将 DropDownList 样式与常规 DropDown 样式组合框进行比较:

Comparing the DropDownList style to the DropDown style under Windows Vista or later

在视觉上,这两个组合框在早期版本的 Windows 中看起来相同,但在 Vista 和更高版本中则不同。 显示自定义前景色的关键是更改 DropDownStyle property将您的组合框控件设置为 DropDown(这实际上是默认设置)。

我也喜欢设置 FlatStyle propertySystem 以便您获得 native 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 showing selected text in red

关于c# - 如何更改 ComboBox 的选定项的 ForeColor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5312825/

相关文章:

javascript - 在 Gridview 中查找按钮并从代码隐藏中单击它(c#)

c# - 如何将 RichTextBox.Text 每个单词的首字母大写?

c# - 为什么 WebBrowser DocumentCompleted 仅在加载所有图像时触发?

c# - 将 DWORD 从 C++ 返回到 C# (DllImport)

c# - 如何按值查找json token,然后删除token

c# - 如何获得 Windows 10 中的默认强调色?

c# - .net 在运行时确定我的应用程序是 exe 还是 web 应用程序

具有属性的类实例化的 C# 到 VB.NET 语法转换

c# - ADOX 表列的 "Nullable"属性?

c# - 使用反射从元数据类中获取属性属性