如何动态更改winforms列表框项的字体?

问题描述 投票:1回答:1

如何在列表框中为可变数量的项目加粗?我已经看过像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);
    }
c# winforms listbox
1个回答
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 []数组绘制字符串。

© www.soinside.com 2019 - 2024. All rights reserved.