我在 C# 平臺上有 winform 專案。我有串列視圖和文本框,如下圖所示。我想根據用戶輸入的文本值對串列重新排序。
我在這里問之前研究過,我通常看到基于再次洗掉和重新添加所有單元到串列視圖的解決方案。我不想這樣做,因為我的串列視圖有太多帶有圖片的專案,因此洗掉和重新添加專案會導致串列視圖作業緩慢。
我想要的是,當用戶在文本框中輸入字符時,以該字符開頭的專案,將此專案置于串列頂部,類似于 google 搜索系統。
我嘗試了下面的代碼,但即使我選擇了索引 0,這也會發送串列末尾的專案。謝謝。

private void txt_search_TextChanged(object sender, EventArgs e)
{
string text = txt_search.Text;
var item = listView1.FindItemWithText(text);
if (item != null)
{
int index = listView1.Items.IndexOf(item);
if (index > 0)
{
listView1.Items.RemoveAt(index);
listView1.Items.Insert(0, item);
}
}
}
uj5u.com熱心網友回復:
ListView使用.Sort()函式排序,不確定默認行為是什么,但我認為您需要一個自定義比較器。
這是(ab)使用ListViewItem.Tag.
自定義比較器:
private class SearchCompare : Comparer<ListViewItem>
{
public override int Compare([AllowNull] ListViewItem x, [AllowNull] ListViewItem y)
{
if (x?.Tag != null && y?.Tag != null)
{
return x.Tag.ToString().CompareTo(y.Tag.ToString());
}
return 0;
}
}
初始化ListView:
var items = new[]
{
"1 no",
"2 yes",
"3 no",
"4 yes"
};
foreach (var item in items)
{
listView1.Items.Add(item);
}
listView1.ListViewItemSorter = new SearchCompare(); // custom sorting
當然,文本更改事件處理程式:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string text = textBox1.Text;
foreach (ListViewItem item in listView1.Items)
{
if (item.Text.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) > -1)
{
item.Tag = "a"; // a is sorted before b
}
else
{
item.Tag = "b"; // b is sorted after a
}
}
listView1.Sort();
}
在搜索文本框中鍵入“yes”將在專案 1 和 3 之前對專案 2 和 4 進行排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381478.html
上一篇:回圈時將欄位和值添加到陣列?
