【问题标题】:How do I dynamically change the font of winforms listbox item?如何动态更改 winforms 列表框项的字体?
【发布时间】:2018-02-23 20:51:12
【问题描述】:

如何将列表框中的可变数量的项目加粗?我见过像this one 这样的解决方案,但它似乎只有在我确切知道哪些项目在运行前应该是粗体时才有效。这是我的具体情况:

我有一个列表框,其中包含从文件中读取的字符串列表。我有一个搜索栏,输入时会自动将匹配该字符串的项目移动到列表框的顶部。不幸的是,位于顶部并不足以作为“搜索结果”的指标,所以我也想让这些项目加粗。在运行之前,我确实知道我想要加粗的所有项目都将位于列表的顶部,但我不知道会有多少项目。此外,当用户删除搜索栏的内容时,列表将重新排序为其初始顺序,并且粗体项目不应变为粗体。

如何在运行时在特定列表框项目的粗体/非粗体之间来回切换?

这是我的搜索和显示功能代码:

    private void txtSearch_TextChanged(object sender, EventArgs e)
    {
        string searchTerm = txtSearch.Text.Trim();
        if(searchTerm.Trim() == "") // If the search box is blank, just repopulate the list box with everything
        {
            listBoxAllTags.DataSource = fullTagList;
            return;
        }

        searchedTagList = new List<UmfTag>();
        foreach(UmfTag tag in fullTagList)
        {
            if(tag.ToString().ToLower().Contains(searchTerm.ToLower()))
            {
                searchedTagList.Add(tag);
            }
        }

        // Reorder the list box to put the searched tags on top. To do this, we'll create two lists:
        // one with the searched for tags and one without. Then we'll add the two lists together.
        List<UmfTag> tempList = new List<UmfTag>(searchedTagList);
        tempList.AddRange(fullTagList.Except(searchedTagList));
        listBoxAllTags.DataSource = new List<UmfTag>(tempList);
    }

【问题讨论】:

  • 首先发布您移动项目以响应搜索的代码。
  • @MarkBenningfield 我已经编辑了我的原始帖子以包含搜索代码。
  • 只需将searchedTagList 维护为表单上的私有字段,当您处理DrawItem 事件时(如您链接到的其他答案),检查该项目是否在搜索到的列表。如果是,请将其绘制为粗体。
  • 感谢您的建议!这类似于我在发布这个问题后终于能够想到的解决方案。但是,我没有查看该项目是否存在于列表中,而是只对开头的所有 n 个项目执行此操作,因为我知道所有搜索结果都在开头。
  • 嘿,随便吧!

标签: c# winforms listbox


【解决方案1】:

我能够解决我自己的问题。我确实使用了this question 中的解决方案,但我改变了它:

    private void listBoxAllTags_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground();
        FontStyle fontStyle = FontStyle.Regular;
        if(e.Index < searchedTagList.Count)
        {
            fontStyle = FontStyle.Bold;
        }
        if(listBoxAllTags.Items.Count > 0) // Without this, I receive errors
        {
            e.Graphics.DrawString(listBoxAllTags.Items[e.Index].ToString(), new Font("Arial", 8, fontStyle), Brushes.Black, e.Bounds);
        }
        e.DrawFocusRectangle();
    }

需要第二个 if 语句(检查计数是否大于 0)。没有它,我收到“index[-1]”错误,因为我的程序首先从空列表框开始,并且 DrawString 方法无法为空 listBox.Items[] 数组绘制字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2015-05-24
    • 2015-03-12
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多