Set the font and color of a listbox item by code in C#(在 C# 中通过代码设置列表框项的字体和颜色)
问题描述
我正忙于一个自定义列表框,我在 C# 中用作寄存器阅读器.现在我想在一个确定的项目中设置一个确定的项目,其字体和颜色与其他项目不同.我检查了 这个问题 并从我所做的答案中以下代码:
I'm busy with a customized list box that I use as a register reader in c#. Now I want to set a determined item in a determined item with a different font and color than the rest. I checked This question and from the answers I made the following code:
private void myListBox_DrawItem(object sender, System.Windows.Forms.DrawItemEventArgs e)
{
e.DrawBackground();
Font myFont;
Brush myBrush;
int i = e.Index;
if (e.Index == 3)
{
myFont = e.Font;
myBrush = Brushes.Black;
}
else
{
myFont = new Font("Microsoft Sans Serif", 9.75f, FontStyle.Bold);
myBrush = Brushes.CadetBlue;
}
e.Graphics.DrawString(myListBox.Items[i].ToString(), myFont, myBrush, e.Bounds, StringFormat.GenericDefault);
}
然后在我的 IntializeComponent() 中调用方法
And call the method in my IntializeComponent() using
this.myListBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.myListBox_DrawItem);
该调用不会引发任何异常,但我看不到我想要处理的行有任何变化.有什么我遗漏的吗?
The call does not throw an exception whatsoever, but I see no change on the line I want to handle. Is there something I am missing?
推荐答案
您的 IntializeComponent()
中又少了一行:
You are missing one more line in your IntializeComponent()
add this:
this.myListBox.DrawMode = DrawMode.OwnerDrawFixed;
在附加事件之前.
这篇关于在 C# 中通过代码设置列表框项的字体和颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中通过代码设置列表框项的字体和颜色


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01