I have a listview and a search textbox. When I type any character or symbol into the textbox, then it matches the typed text with the listbox items. If there is any match then it highlights the matched item. In that point, I want to remove the not matched items from the listview. Only the matched items will remain in the listview. What do you recommend me to solve that ? My other code is below.
private void TxtSearch_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
ListControl lc = getactivListview();
FindListViewItem(lc);
}
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));
}
}
}
}
Well, the easiest and most natural way in
WPFis use of databinding and filterModelViewcollection on it.for example:
You bind to view
GetData()which return either full or filtered collection, based on the absence or presence of the filter string.Like an example how can be databinding implemented on
ListView(it’s not a shot topic and hardly can be explained in this simple answer), can have a look on: Data Binding in WPF ListView