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# 中通过代码设置列表框项的字体和颜色


基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01