C#实现ListBox指定项加粗、移除项及添加空项
解决方案
1. 移除红色标记区域的项
先明确红色区域对应的项(比如通过文本匹配或索引范围),倒序遍历ListBox的项集合避免索引错乱,移除符合条件的项:
// 示例:移除文本为"RedItem1"、"RedItem2"的项(替换成你红色区域的实际项文本) for (int i = ListBox1.Items.Count - 1; i >= 0; i--) { string itemText = ListBox1.Items[i].ToString(); if (itemText == "RedItem1" || itemText == "RedItem2") { ListBox1.Items.RemoveAt(i); } }
如果是按索引范围移除(比如红色区域是索引5到7),同样倒序删除:
for (int i = 7; i >= 5; i--) { ListBox1.Items.RemoveAt(i); }
2. 将蓝色标记区域的项设置为加粗
修改你的ListBox1_DrawItem事件,判断当前项是否属于蓝色区域(比如从"Client"到"MAT",或到第一个空项),根据判断结果使用普通或加粗字体:
private void ListBox1_DrawItem(object sender, DrawItemEventArgs e) { ListBox lb1 = (ListBox)sender; if (e.Index < 0) return; // 防止索引越界 string itemText = lb1.Items[e.Index].ToString(); // 定义字体:默认普通,蓝色区域项用加粗 Font drawFont; // 判断是否属于蓝色区域(示例:从"Client"开始到"MAT"结束) int clientIndex = lb1.Items.IndexOf("Client"); int matIndex = lb1.Items.IndexOf("MAT"); bool isBlueArea = clientIndex != -1 && matIndex != -1 && e.Index >= clientIndex && e.Index <= matIndex; drawFont = isBlueArea ? new Font("Arial", 10, FontStyle.Bold) : new Font("Arial", 10, FontStyle.Regular); e.DrawBackground(); e.Graphics.DrawString(itemText, drawFont, Brushes.Black, e.Bounds); e.DrawFocusRectangle(); drawFont.Dispose(); // 释放字体资源,避免内存泄漏 }
3. 在MAT项与LBL1项之间添加两个空项
先找到"MAT"的索引,然后在其后方插入两个空字符串:
int matIndex = ListBox1.Items.IndexOf("MAT"); if (matIndex != -1 && matIndex < ListBox1.Items.Count - 1) { // 在MAT后插入两个空项 ListBox1.Items.Insert(matIndex + 1, ""); ListBox1.Items.Insert(matIndex + 2, ""); }
整合后的完整代码示例
public partial class Form1 : Form { public Form1() { InitializeComponent(); ListBox1.DrawMode = DrawMode.OwnerDrawFixed; // 窗体加载时执行操作:移除红色项、添加空项 RemoveRedItems(); AddEmptyItemsBetweenMatAndLbl1(); } private void RemoveRedItems() { // 替换成你红色区域的实际项判断条件 for (int i = ListBox1.Items.Count - 1; i >= 0; i--) { string itemText = ListBox1.Items[i].ToString(); if (itemText == "RedItem1" || itemText == "RedItem2") { ListBox1.Items.RemoveAt(i); } } } private void AddEmptyItemsBetweenMatAndLbl1() { int matIndex = ListBox1.Items.IndexOf("MAT"); if (matIndex != -1 && matIndex < ListBox1.Items.Count - 1) { ListBox1.Items.Insert(matIndex + 1, ""); ListBox1.Items.Insert(matIndex + 2, ""); } } private void ListBox1_DrawItem(object sender, DrawItemEventArgs e) { ListBox lb1 = (ListBox)sender; if (e.Index < 0) return; string itemText = lb1.Items[e.Index].ToString(); Font drawFont; // 判断蓝色区域项(Client到MAT之间的项) int clientIndex = lb1.Items.IndexOf("Client"); int matIndex = lb1.Items.IndexOf("MAT"); bool isBlueArea = clientIndex != -1 && matIndex != -1 && e.Index >= clientIndex && e.Index <= matIndex; drawFont = isBlueArea ? new Font("Arial", 10, FontStyle.Bold) : new Font("Arial", 10, FontStyle.Regular); e.DrawBackground(); e.Graphics.DrawString(itemText, drawFont, Brushes.Black, e.Bounds); e.DrawFocusRectangle(); drawFont.Dispose(); } }
内容的提问来源于stack exchange,提问作者Wadim
相关产品推荐
相关产品推荐

