我正在做一场比赛。我有一个用户列表(缺口):
List<string> users;
此列表用于向ListBox上的用户显示,请致电listaJogadores
。
public delegate void actualizaPlayersCallback(List<string> users);
public void actualizaPlayers(List<string> users)
{
listaJogadores.BeginInvoke(new actualizaPlayersCallback(this.actualizarListaPlayers), new object[] { users });
}
public void actualizarListaPlayers(List<string> users)
{
listaJogadores.Items.Clear();
for (int i = 0; i < users.Count; i++)
{
listaJogadores.Items.Add(users.ElementAt(i));
}
}
当用户正在玩游戏时,它在游戏列表中有缺口:
List<Game> games;
我想要的是当玩家进入游戏时,listaJogadores
中的昵称颜色必须为红色!
当我在游戏中只有一个玩家时,一切正常,所有玩家都看到该玩家的昵称是红色的,但当另一个玩家进入游戏时,我在指令中得到 ArgumentOutOfRangeException string nick = tmp.players.ElementAt(i).getNick();
这是我的代码......请给我一些想法/帮助!我认为问题是for()
,但是如何在不进行循环的情况下操纵整个列表呢?
listaJogadores.DrawMode = DrawMode.OwnerDrawFixed;
private void listaJogadores_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
Brush textBrush = SystemBrushes.ControlText;
Font drawFont = e.Font;
for (int i = 0; i < games.Count; i++)
{
Game tmp;
tmp = games.ElementAt(i);
for (int j = 0; j < tmp.players.Count; j++)
{
string nick = tmp.players.ElementAt(i).getNick();
if (listaJogadores.Items[e.Index].ToString() == nick)
{
textBrush = Brushes.Red;//RED....
if ((e.State & DrawItemState.Selected) > 0)
drawFont = new Font(drawFont.FontFamily, drawFont.Size, FontStyle.Bold);
}
else if ((e.State & DrawItemState.Selected) > 0)
{
textBrush = SystemBrushes.HighlightText;
}
}
}
e.Graphics.DrawString(listaJogadores.Items[e.Index].ToString(), drawFont, textBrush, e.Bounds);
}
答案 0 :(得分:1)
您不应该在循环中放置绘图逻辑,因为您只想定义画笔一次。首先确定该项目是否是实际游戏中的玩家。然后用正确的颜色绘制项目:
private void listaJogadores_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index >= 0 && e.Index < listaJogadores.Items.Count) {
e.DrawBackground();
Brush textBrush = SystemBrushes.ControlText;
Font drawFont = e.Font;
bool playerFound = false;
string nick = (string)listaJogadores.Items[e.Index];
foreach (Game game in games) {
if (game.players.Any(p => p.getNick() == nick)) {
playerFound = true;
break;
}
}
if (playerFound) {
textBrush = Brushes.Red; //RED....
if ((e.State & DrawItemState.Selected) > 0)
drawFont = new Font(drawFont.FontFamily, drawFont.Size, FontStyle.Bold);
} else if ((e.State & DrawItemState.Selected) > 0) {
textBrush = SystemBrushes.HighlightText;
}
e.Graphics.DrawString(nick, drawFont, textBrush, e.Bounds);
e.DrawFocusRectangle();
}
}
并测试e.Index是否有效。这可能会导致您的“索引超出范围”异常。
答案 1 :(得分:0)
检查此代码:
private void listaJogadores_DrawItem(object sender, DrawItemEventArgs e)
{
listaJogadores.DrawItem-=Eeventhandle(listaJogadores_DrawItem);
.
.
.
listaJogadores.DrawItem+=Eeventhandle(listaJogadores_DrawItem);
}