【发布时间】: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 个项目执行此操作,因为我知道所有搜索结果都在开头。
-
嘿,随便吧!