如何在Windows Forms的CheckBoxList中自定义项的显示位置
解决CheckBoxList项间距与复选框文本空隙问题
原代码
// 如何将项绘制到指定位置 private static int topOffset = 30; private static int leftOffset = 30; private void FoldersToClearItem_Position(string item) { Point newPosition = new Point(leftOffset, topOffset); } // 创建目录并设置checkedBoxList1的项,该CheckBoxList已重命名为FoldersToClear private void ZzCleaner_Load(object sender, EventArgs e) { 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 folderOrganiser = new FolderOrganiser(item, richTextBox1); } var index = this.FoldersToClear.Items.IndexOf(item); FoldersToClear.SetItemChecked(index, checkbox); }); } }
用户问题
我始终无法找到在CheckBoxList中自定义项位置的解决方案。上述代码实现了程序加载时从配置中恢复关闭前标记的复选框项及选中状态的功能。
我的问题是:如何让项与控件边框保持一定间距,或者说,如何在复选框与项文本之间增加空隙?
解决方案
方法1:自定义绘制(精准控制所有间距)
默认CheckBoxList没有直接设置间距的属性,需通过自定义绘制实现:
- 先将CheckBoxList的
DrawMode属性设置为OwnerDrawFixed - 绑定
DrawItem事件,手动绘制每个项来控制间距:
private void FoldersToClear_DrawItem(object sender, DrawItemEventArgs e) { if (e.Index < 0) return; // 清空当前项区域背景 e.DrawBackground(); // 获取当前项选中状态 bool isChecked = FoldersToClear.GetItemChecked(e.Index); // 绘制复选框,调整X/Y值控制项与控件边框的间距 CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(e.Bounds.X + 10, e.Bounds.Y + 5), isChecked ? System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal : System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal); // 绘制文本,调整X值控制复选框与文本的空隙 TextRenderer.DrawText(e.Graphics, FoldersToClear.Items[e.Index].ToString(), e.Font, new Point(e.Bounds.X + 35, e.Bounds.Y + 3), e.ForeColor); // 绘制焦点框(可选) e.DrawFocusRectangle(); }
方法2:调整控件内边距(快速实现整体边框间距)
如果只需要项与控件边框的整体间距,直接设置Padding属性即可:
// 左、上各留10像素间距,按需调整数值 FoldersToClear.Padding = new Padding(10, 10, 0, 0);
注:此方法无法单独调整复选框与文本的空隙,仅控制整体内边距。
注意事项
- 使用自定义绘制时,必须确保
DrawMode设置为OwnerDrawFixed,否则事件不会触发 - 代码中的数值(如10、35)可根据实际需求修改,达到理想的间距效果
内容的提问来源于stack exchange,提问作者Marcel Majhenic
相关产品推荐
相关产品推荐

