c# - 在 ComboBox 中显示颜色列表 - 颜色选择器
问题描述
] 想ComboBox
用所有颜色的列表填充我。我期待像这样的东西:
CBcolor.DataSource = AllColor;
然后我想像这样使用我的 ComboBox:
Color selected = CBcolor.selectedvalue;
C_ObjetGraphique cercle = new dessin.Cercle(e.Location, selected, selected, 100);
cercle.Affiche();
ledessin.ajoute(cercle);
如何在我ComboBox
的颜色选择器中显示颜色列表?
解决方案
一般来说,您需要将颜色列表设置为组合框的数据源。您可能有一些预定义颜色的列表,例如 Color.Red、Color.Green、Color.Blue;您可以依赖KnownColor
,或者您可以使用反射来获取类型Color
的属性Color
。
在此示例中,我使用该Color
类型的颜色属性来显示一个组合框,如下所示:
获取颜色列表并设置组合框的数据源:
comboBox1.DataSource = typeof(Color).GetProperties()
.Where(x => x.PropertyType == typeof(Color))
.Select(x => x.GetValue(null)).ToList();
处理组合框的自定义绘制:
comboBox1.MaxDropDownItems = 10;
comboBox1.IntegralHeight = false;
comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.DrawItem += comboBox1_DrawItem;
然后为comboBox1_DrawItem
:
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
if (e.Index >= 0)
{
var txt = comboBox1.GetItemText(comboBox1.Items[e.Index]);
var color = (Color)comboBox1.Items[e.Index];
var r1 = new Rectangle(e.Bounds.Left + 1, e.Bounds.Top + 1,
2 * (e.Bounds.Height - 2), e.Bounds.Height - 2);
var r2 = Rectangle.FromLTRB(r1.Right + 2, e.Bounds.Top,
e.Bounds.Right, e.Bounds.Bottom);
using (var b = new SolidBrush(color))
e.Graphics.FillRectangle(b, r1);
e.Graphics.DrawRectangle(Pens.Black, r1);
TextRenderer.DrawText(e.Graphics, txt, comboBox1.Font, r2,
comboBox1.ForeColor, TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
}
}
从组合框中获取选定的颜色:
if(comboBox1.SelectedIndex>=0)
this.BackColor = (Color)comboBox1.SelectedValue;
推荐阅读
- jquery - 表达式语言代码显示为纯文本 JSP
- function - return_of_invalid_type 返回类型“String”不是“void”,由方法“getData”定义
- python - 即使在更新数据库后,SQLAlchemy 也不会在我的表中找到该列?
- angular - 由于 Firebase 的 IDBIndex 错误,无法提供服务器呈现的应用程序
- java - 如何将 Swing 小部件插入 SWT 我在使用 SWT_AWT.new_Frame 时在线程“main”java.lang.IllegalArgumentException 中出现异常
- angular - Ngrx,Rxjs - 合并可观察的流返回一个新的流
- angular - 子节点出现在每个父节点中
- php - 如何为已在 phpunit 中初始化的 MockObject 实例设置动态属性
- angular - 在 Angular 后端的每个服务上出现 403 错误是在 laravel
- android - 所需类型与找到的不同