user1137543
user1137543

Reputation: 3

Search the databound list box using a text box in wpf

I have a list-box where items are loaded from a class(contactclass) , i want to make a text box when the user types anything in text-box, list-box should search the starting characters entered and display it in the listbox? this is some of my code

<Window.DataContext>
    <local:AddressBookViewModel  x:Name="ViewModel"/>
</Window.DataContext>

The text box for search

<TextBox  Name="txtNameToSearch" HorizontalAlignment="Right" Height="26" Margin="0,18,68,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="160" BorderThickness="3" Text="{Binding ___No_Name_}" TextChanged="TextBox_TextChanged">

The listbox

<ListBox  IsTextSearchEnabled="True"   x:Name="___No_Name_" HorizontalAlignment="Left" Margin="37,71,0,47" Width="217" ItemsSource="{Binding Contacts, Mode=TwoWay}" SelectedItem="{Binding SelectedContact,Mode=TwoWay}" Opacity="0.495" DisplayMemberPath="Name" FontFamily="Verdana" FontWeight="Bold" >

Pleas can anyone tell me what i should do next ?

Upvotes: 0

Views: 2447

Answers (1)

Thelonias
Thelonias

Reputation: 2935

The way I would handle this is to have some "search string" property on your viewmodel that you bind the text of your TextBox to:

private _someString = string.Empty;
public SomeString
{
  get { return _someString; }
  set 
  {
     _someString = value;
     DoSearch();
  }
}

XAML:

<TextBox Text={Binding Path="SomeString", Mode=OneWayToSource}/>

You shouldn't need the "TextChanged" event.

Then, in your public properties "Set" section on your viewmodel, you can call a search method you make which will fill some ObservableCollection with results. This same collection will be the ItemsSource of your ListBox.

To recap: You'll have some master collection of data you want to search. When you type in the textbox, the search method get's called, filling another collection with the results that match your search.

The solution I gave is only single threaded, and will lock up your GUI while performing your searches, so I'd recommend pushing the search off onto another thread. If you do this, you'll need make sure that the thread that creates your ObservableCollection (probably your GUI thread) is the same thread that adds the results...this is because you can't modify an ObservableCollection on a thread different than the one it was created on.

Another option is exploring CollectionView and it's filtering capabilities.

Upvotes: 1

Related Questions