c# - 更改在 ListBox WindowsForm C# 中选择的颜色行项目
问题描述
我尝试通过此代码(c#、windowsform、VS2017):
dynamic model;
private void ListBox_DrawItem(object sender, DrawItemEventArgs e)
{
try
{
if (e.Index < 0) return;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
e = new DrawItemEventArgs(e.Graphics,
e.Font,
e.Bounds,
e.Index,
e.State ^ DrawItemState.Selected,
e.ForeColor,
Color.LimeGreen);
e.DrawBackground();
e.Graphics.DrawString(listBox.Items.OfType<Game>().Select(table => table.name).ElementAt(e.Index), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "MainForm.ListBox_DrawItem()", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
将我的 ListBox 的所选项目的行的颜色(默认为蓝色)更改为另一种颜色(此处为绿色)
这是渲染: LisBox:更改选定的颜色项
但我想用一个开关在 4 个不同的对象之间进行选择,但没有其他的工作:
dynamic model;
private void ListBox_DrawItem(object sender, DrawItemEventArgs e)
{
try
{
if (e.Index < 0) return;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
e = new DrawItemEventArgs(e.Graphics,
e.Font,
e.Bounds,
e.Index,
e.State ^ DrawItemState.Selected,
e.ForeColor,
Color.LimeGreen);
e.DrawBackground();
switch (selectedModel)
{
case "Game":
model = listBox.Items.Cast<Game>().Select(table => table.name).ElementAt(e.Index);
break;
case "Gender":
model = listBox.Items.Cast<Gender>().Select(table => table.name).ElementAt(e.Index);
break;
}
e.Graphics.DrawString(model, e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
我尝试使用但没有成功:OfType <> 和 Cast <>
model = listBox.Items.Cast<Game>().Select(table => table.name).ElementAt(e.Index);
或者
model = listBox.Items.OfType<Game>().Select(table => table.name).ElementAt(e.Index);
异常:System.Core.dll 中的“System.InvalidCastException”
感谢您的帮助,如果我不够清楚,我会提前原谅我自己尝试将图片简化为我的请求。
编辑:
我回答自己,这可能有不止一个帮助!我最终找到了一个解决方案(但我认为不是很干净),她在那里:
if (listBox.SelectedItem.GetType() == typeof(Game))
{
e.Graphics.DrawString(listBox.Items.Cast<Game>().Select(table => table.name).ElementAt(e.Index), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
if (listBox.SelectedItem.GetType() == typeof(Gender))
{
e.Graphics.DrawString(listBox.Items.Cast<Gender>().Select(table => table.name).ElementAt(e.Index), e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
显然开关不起作用,但我不明白为什么?
所以如果你有更好的想法让它更紧凑和优雅,我是一个接受者!谢谢你们,
解决方案
推荐阅读
- javascript - 使用 vue.js 将 API 数据保存到数组中
- reporting-services - 远程链接服务器上的 SSRS 查询
- mysql - MYSQL HAVING (not) with ROW_NUMBER() 为什么它返回不同的行数
- curve-fitting - 模拟数据的曲线拟合不起作用
- jenkins - 神器收集问题
- qt - 为什么 QT GUI 对流程图性能的影响如此之大?
- amazon-web-services - 何时应该使用自动缩放以及何时使用 SQS?
- javascript - treeshake后如何在webpack中获取包中的文件列表
- python - Guido van Rossum 在哪里以及在什么情况下说“如果你希望你的代码运行得更快,你应该只使用 PyPy。”?
- html - 如何在链接下添加一个点