Tuesday, 10 September 2013

How to display objects from an observablecollection in a listbox based on a search string?

How to display objects from an observablecollection in a listbox based on
a search string?

Thank you for reading my question.
The situation:
I have an ObservableCollection<CheckableListItem<T>> CheckableItems
The class CheckableListItem<T> has 2 elements: bool IsChecked and T Item.
The class acts as a wrapper class that adds a checkbox to each Item. In
this project the Item passed has a string element called Name.
How it is displayed in XAML code:
<ListBox ItemsSource="{Binding CheckableItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked, Mode=TwoWay}"
Content="{Binding Path=Item.Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This gives me a Listbox with every entry containing a checkbox and the
content of the checkbox is the Item.Name string.
The problem:
I have added a textbox in XAML <TextBox></TextBox> And Now I would like
the listbox to only display the objects from the observable collection
which match the text from the TextBox.
How I think it could be done:
Create a view of some kind to bind to the listbox and update the view with
only the objects that match the search criteria. If no text is entered in
the searchbox then all object must be displayed, If only the letter E for
example is entered, only the objects containing a letter E in the
Item.Name property should be displayed.
I think best would be to bind the text to a string variable in my
datacontext and fire an event each time the string changes, something like
this:
<TextBox Text="{Binding Path=SearchString,
UpdateSourceTrigger=PropertyChanged}" TextChanged="TextBox_TextChanged" />
The function:
private void TextBox_TextChanged(object sender,
System.Windows.Controls.TextChangedEventArgs e)
{
// Called each time the text changes, perform search here?
}
I just lack the knowledge of WPF syntax for how to create this or how to
google the right terms.
Any input is welcome. Thanks in advance.

No comments:

Post a Comment