[英]How do I change a console application to send the output to a winforms listbox?
[英]How do I dynamically change the font of winforms listbox item?
如何在列表框中將可變數量的項目加粗? 我見過類似的解決方案這一項,但如果我確切地知道哪些項目應該是在運行之前大膽的似乎只有工作。 這是我的具體案例:
我有一個列表框,其中包含從文件中讀取的字符串列表。 我有一個搜索欄,當輸入時,它會自動將匹配該字符串的項目移動到列表框的頂部。 不幸的是,處於頂部並不足以作為“搜索結果”的指標,因此我還想將這些項目加粗。 在運行之前,我確實知道我想要加粗的所有項目都在列表的頂部,但我不知道會有多少項目。 此外,當用戶刪除搜索欄的內容時,列表將重新排序為其初始順序,並且粗體項目不應變為粗體。
如何在運行時在特定列表框項目的粗體/非粗體之間來回切換?
這是我的搜索和顯示功能代碼:
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);
}
我能夠解決我自己的問題。 我確實使用了這個問題中的解決方案,但我像這樣改變了它:
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[] 數組繪制字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.