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# 中通过代码设置列表框项的字体和颜色
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
