如何设置列表框单个元素的前景色
本文关键字:单个 元素 前景色 列表 何设置 设置 | 更新日期: 2023-09-27 18:15:06
我在做游戏。我有一个用户列表(尼克斯):
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));
}
}
当用户在玩游戏时,那么它在游戏列表中有一个nick:
List<Game> games;
我想要的是当玩家进入游戏时,他在listaJogadores
中的nick显示的颜色必须是红色!当我在游戏中只有一个玩家时,一切都很好,所有玩家都看到那个玩家的红色标记,但是当另一个玩家进入游戏时,我在指令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);
}
你不应该把绘图逻辑放在循环中,因为你只想定义一次画笔。首先确定道具是否属于实际游戏中的玩家。然后用正确的颜色绘制项目:
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.i dex是否有效。这可能会导致"Index is out of bounds"异常。
检查此代码:
private void listaJogadores_DrawItem(object sender, DrawItemEventArgs e)
{
listaJogadores.DrawItem-=Eeventhandle(listaJogadores_DrawItem);
.
.
.
listaJogadores.DrawItem+=Eeventhandle(listaJogadores_DrawItem);
}