如何更改WindowsForms中CheckedListBox中SelectedItem的颜色?
我想更改 C# WindowsForms 中 CheckedListBox 中选中的项目的颜色。
任何人都可以帮我解决这个问题吗!
I want to change the color of the items that are chedked in the CheckedListBox in C# WindowsForms.
Can any one help me to solve this problem!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可以帮助您开始。我对
CheckedListBox
进行了子类化并覆盖了绘图事件。结果是列表中所有选中的项目都以红色背景绘制。通过尝试,如果您希望复选框后面的区域也具有不同的颜色,请在调用
base.OnDrawItem
之前使用e.Graphics.FillRectangle
。This should get you started. I've subclassed a
CheckedListBox
and overridden the drawing event. The result is all checked items in the list are drawn with a red background.From playing around with this, if you want the area behind the checkbox to be a different colour as well, use
e.Graphics.FillRectangle
before callingbase.OnDrawItem
.感谢乔恩,他让我走上了正确的道路,因为我有同样的愿望:让项目的文本颜色对于复选框的 3 种状态中的每一种都不同。
我想出了 CheckedListBox 的这个子类。它更改项目文本,而不是背景颜色。它允许用户在设计时或当然在代码中设置 3 种颜色。
它还修复了我在设计器中查看控件时出现错误的问题。我还必须克服我认为在您的解决方案中会发生的问题,如果选择了该项目,则 base.OnDrawItem 方法会消除覆盖的 OnDrawItem 方法中设置的颜色选择。我这样做的代价是所选项目不再具有彩色背景,方法是删除 e.State 中表示已选择的部分,以便在 base.OnDrawItem 中它不会成为所选项目的外观和感觉。不过我认为这没关系,因为用户仍然会看到焦点矩形,它指示哪个被选中。
希望这对其他人有用。在网上查找时,我没有找到太多有凝聚力的解决方案(甚至只是一个完整的 OnDrawItem 方法)。
Thanks Jon that got me on the right path as I had the same desire: to have the item's text color be different for each of the 3 states of the checkbox.
I came up with this subclass of the CheckedListBox. It changes the items text, not the background color. It lets the 3 colors be set by the user at design time or in code of course.
It also fixes a problem I had where I got an error when viewing the control in the designer. I also had to overcome a problem I think would have happened in your solution where if the item is selected the base.OnDrawItem method obliterates the color choices set in the overridden OnDrawItem method. I did this at the expense of the selected item no longer having a colored background by removing the part of e.State that says it is selected so that in the base.OnDrawItem it is not made to be a selected item look and feel. This is ok though I think since the user will see the focus rectangle still which indicates which is selected.
Hopefully this may be useful to others. I didn't find much for a cohesive solution (even just a complete OnDrawItem method) when looking on the net.