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

时间:2018-02-23 20:51:13

标签: c# winforms listbox

如何在列表框中为可变数量的项目加粗?我已经看过像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);
    }

1 个答案:

答案 0 :(得分: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)。没有它,我收到了#34; index [-1]&#34;错误,因为我的程序首先以空列表框开始,而DrawString方法无法为空listBox.Items []数组绘制字符串。

相关问题