我有一個包含客戶信息的listview。該列表視圖上方有一個搜索文本框。當你在文本框中輸入任何內容時,它會在列表視圖中突出顯示匹配的項目。但是,問題在於它只能在列表視圖的視覺方面進行搜索。它不會在列表視圖的不滾動的一側進行搜索(listview的按鈕)。我的代碼如下。請看一看。WPF Listview item highlighting
private void FindListViewItem(DependencyObject obj)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
ListViewItem lv = obj as ListViewItem;
if (lv != null)
{
HighlightText(lv);
}
FindListViewItem(VisualTreeHelper.GetChild(obj as DependencyObject, i));
}
}
private void HighlightText(Object itx)
{
if (itx != null)
{
if (itx is TextBlock)
{
Regex regex = new Regex("(" +TxtSearch.Text + ")", RegexOptions.IgnoreCase);
TextBlock tb = itx as TextBlock;
if (TxtSearch.Text.Length == 0)
{
string str = tb.Text;
tb.Inlines.Clear();
tb.Inlines.Add(str);
return;
}
string[] substrings = regex.Split(tb.Text);
tb.Inlines.Clear();
foreach (var item in substrings)
{
if (regex.Match(item).Success)
{
Run runx = new Run(item);
runx.Background = Brushes.Lime;
tb.Inlines.Add(runx);
if (tb.IsMouseOver)
{
tb.IsEnabled = false;
}
}
else
{
tb.Inlines.Add(item);
tb.IsEnabled = false;
}
}
return;
}
else
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(itx as DependencyObject); i++)
{
HighlightText(VisualTreeHelper.GetChild(itx as DependencyObject, i));
}
}
}
}
此外,默認情況ListView控件使用虛擬化,這意味着並不是所有的項目都被繪製出來,所以你的方法在這種情況下是行不通的。 –
正在使用MVVM方法嗎?你有綁定視圖模型? – Sisyphe
@AdrianFaciu那麼你有什麼建議嗎? – Omnipotent