我一直试图在列表框中添加不同颜色的项目,并偶然发现this Link。我尝试将其实施到我的项目中。但是现在我有一个大问题:列表框的数据源是一个绑定列表,并且具有正常工作的Displaymember和所有内容,但是在插入此内容之后(这是进行颜色更改所必需的):
lbx_robots.DrawMode = DrawMode.OwnerDrawFixed;
[显示成员似乎被忽略了,没有看到项目的名称,而是看到了Robogotchi.Robot,这与我完全没有显示成员时相同。
大多数问题代码所在的类:
public Robogotchi()
{
InitializeComponent();
//test BEGIN; DELETE LATER
Robot robot = new Robot();
robot.State = Robot.stateofrobot.Einwandfrei;
robot.Name = "test";
int abc = Convert.ToInt32(robot.State);
robotlist.Add(robot);
lbx_robots.DataSource = robotlist;
lbx_robots.DisplayMember = "Name";
lbx_robots.Refresh();
//test END; DELETE LATER
//stuff to change the color of listbox items
//lbx_robots.BackColor = Color.Beige;
lbx_robots.DrawMode = DrawMode.OwnerDrawFixed;
lbx_robots.DrawItem += new DrawItemEventHandler(listBox1_SetColor);
}
这是我运行它后在列表框中显示的内容:Screenshot of my Listbox with displaymember not working
编辑:我刚刚解决了它:在网站的代码中,有一行显示
.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
当我将其更改为:
e.Graphics.DrawString((((ListBox)sender).Items[e.Index] as Robot).Name,
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
有效。