【发布时间】:2015-08-20 10:05:53
【问题描述】:
我正在使用 VS 2015 在 C# 中编写客户端/服务器 WinForms 应用程序。
我有一个 ListBox 控件,它的 DrawItem 事件是 owner-drawn(是的,我设置了 DrawMode OwnerDrawFixed) 的属性,每次收到新消息时都必须重新绘制。
我在这个reference 之后使用这个回调:
private void chatLobby_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
int ItemMargin = 0;
string last_u = "";
foreach(Message m in ChatHistory[activeChatID])
{
// Don't write the same user name
if(m.from.name != last_u)
{
last_u = m.from.name;
e.Graphics.DrawString(last_u, ChatLobbyFont.Username.font, ChatLobbyFont.Username.color, e.Bounds.Left, e.Bounds.Top + ItemMargin);
ItemMargin += ChatLobbyFont.Message.font.Height;
}
e.Graphics.DrawString(" " + m.message, ChatLobbyFont.Message.font, ChatLobbyFont.Message.color, e.Bounds.Left, e.Bounds.Top + ItemMargin);
ItemMargin += ChatLobbyFont.Message.font.Height;
}
e.DrawFocusRectangle();
}
这就是 MeasureItem 方法:
private void chatLobby_MeasureItem(object sender, MeasureItemEventArgs e)
{
// No messages in the history
if(ChatHistory[activeChatID][0] == null)
{
e.ItemHeight = 0;
e.ItemWidth = 0;
}
string msg = ChatHistory[activeChatID][e.Index].message;
SizeF msg_size = e.Graphics.MeasureString(msg, ChatLobbyFont.Message.font);
e.ItemHeight = (int) msg_size.Height + 5;
e.ItemWidth = (int) msg_size.Width;
}
使用ListBox.Add() 接收并插入消息,它确实有效,由调试器确认。
但 ListBox 仅在我单击它时才会重绘(我认为它会触发焦点)。
我已经尝试过.Update()、.Refresh() 和.Invalidate() 没有运气。
有没有办法从代码中触发DrawItem()?
【问题讨论】:
标签: c# .net listbox visual-studio-2015 ondrawitem