【问题标题】:DrawItem event is fired only when the user clicks the ListBox仅当用户单击 ListBox 时才会触发 DrawItem 事件
【发布时间】: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


    【解决方案1】:

    经过一番研究,我找到了解决方案:DrawItem 事件在控件发生更改时被调用。

    事实上,.Add() 可以解决问题。 我用这个改变了我的更新功能:

    private void getMessages()
    {
        // ... <--- connection logic here
    
        chatLobby.Items.Add(" "); // Alters the listbox
    }
    

    【讨论】:

    • 我解决了闪烁问题:我正常添加了列表框中的项目,而不是从ChatHistory读取。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 2017-09-06
    • 1970-01-01
    • 2016-12-18
    • 2017-02-11
    • 2019-07-10
    相关资源
    最近更新 更多