如何为CheckListBox首个项之后的条目设置不同字体样式
WinForms CheckListBox 自定义条目字体实现方案
WinForms 原生的CheckBoxList默认不支持单个条目独立设置字体,要实现首个条目后每个条目用不同字体的需求,必须启用自绘模式(Owner-Draw),具体步骤如下:
1. 开启自绘模式
在你的ZzCleaner_Load方法中添加代码,开启FoldersToClear的自绘模式并绑定绘制事件:
private void ZzCleaner_Load(object sender, EventArgs e) { Region = System.Drawing.Region.FromHrgn(CreateRoundRectRgn(0, 0, Width, Height, 25, 25)); richTextBox1_Load(); // 开启自绘模式 FoldersToClear.DrawMode = DrawMode.OwnerDrawFixed; // 绑定DrawItem事件(也可在设计器中直接绑定) FoldersToClear.DrawItem += FoldersToClear_DrawItem; if (!string.IsNullOrEmpty(Properties.Settings.Default.FoldersToClear)) { Properties.Settings.Default.FoldersToClear.Split(',') .ToList() .ForEach(item => { bool checkbox = false; if (!FoldersToClear.Items.Contains(item)) { FoldersToClear.Items.Add(item); } if (Properties.Settings.Default.CheckedFolders.Contains(item)) { checkbox = true; folderOrganiser = new FolderOrganiser(item, richTextBox1); } var index = this.FoldersToClear.Items.IndexOf(item); FoldersToClear.SetItemChecked(index, checkbox); }); } }
2. 实现DrawItem事件的自定义绘制逻辑
添加FoldersToClear_DrawItem方法,完成每个条目的复选框、文本绘制,并针对首个条目之后的内容设置不同字体:
private void FoldersToClear_DrawItem(object sender, DrawItemEventArgs e) { // 处理无效索引 if (e.Index < 0) return; CheckListBox listBox = sender as CheckListBox; bool isChecked = listBox.GetItemChecked(e.Index); string itemText = listBox.Items[e.Index].ToString(); // 绘制背景:区分选中/未选中状态 e.DrawBackground(); if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds); } else { e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds); } // 绘制复选框 CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(e.Bounds.X, e.Bounds.Y), isChecked ? System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal : System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal); // 设置字体:首个条目用默认字体,后续条目自定义 Font itemFont; if (e.Index == 0) { itemFont = listBox.Font; } else { // 按索引设置不同字体,可根据需求调整规则 switch(e.Index) { case 1: itemFont = new Font("Arial", 10f, FontStyle.Regular); break; case 2: itemFont = new Font("Verdana", 12f, FontStyle.Bold); break; case 3: itemFont = new Font("Microsoft YaHei", 9f, FontStyle.Italic); break; default: itemFont = new Font("Segoe UI", 8f, FontStyle.Regular); break; } } // 绘制文本:偏移位置避开复选框 TextRenderer.DrawText(e.Graphics, itemText, itemFont, new Point(e.Bounds.X + 22, e.Bounds.Y + 2), (e.State & DrawItemState.Selected) == DrawItemState.Selected ? SystemColors.HighlightText : SystemColors.WindowText); // 绘制焦点框(可选) e.DrawFocusRectangle(); // 释放自定义字体资源,避免内存泄漏 if (e.Index != 0) { itemFont.Dispose(); } }
额外说明
- 若需要不同条目有不同高度,将
DrawMode改为OwnerDrawVariable,同时处理MeasureItem事件设置每个条目的高度。 - 自定义字体后务必调用
Dispose()释放资源,防止内存泄漏。 - 复选框的偏移量可根据实际UI调整,确保文本与复选框不重叠。
内容的提问来源于stack exchange,提问作者Marcel Majhenic
相关产品推荐
相关产品推荐

