Snaylor
Snaylor

Reputation: 43

How to filter my WPF-combobox?

first of all: sorry for the bad english, its not my first language.

I am currently working on a project where i have a list of persons which i want to list up in a combobox. I want the combobox to get filtered, so that there are only the people listed up i am searchig for.

For example if i type in the combobox "Joh", there should only be people who start with "Joh" like "John", "Johann", ... .

The next thing is, my combobox is not "editable", how can i make it that i can write in it ? Currently it is "locked" ...

I hope you understand whats my problem, and how to solve it!

Upvotes: 1

Views: 10119

Answers (2)

d.moncada
d.moncada

Reputation: 17402

This is actually built in!

What you need to do is set the following properties on your ComboBox control.

<ComboBox ItemsSource="{Binding PersonList}"
          IsTextSearchEnabled="True" 
          TextSearch.TextPath="Name"/>

This example assumes you have a PersonList of type Person, in which type Person has a property of Name.

You'll want to set the TextSearch.TextPath to whatever property you want to search on (based on a property of the items in your ItemsSource collection).

More info, see https://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.combobox.istextsearchenabled

Upvotes: 0

Kyle Rone
Kyle Rone

Reputation: 305

So one of the cool things about WPF is that it allows for binding. Specifically, binding properties in your code to controls in your UI. So to have a filtered combobox I would bind a list of whatever object you have to your combobox, something like below:

C#:

private List<Person> myList = new List<Person>();
public List<Person> MyList 
{ 
    get { return myList; }
    set { myList = value; }
}

WPF:

<ComboBox Name="cboObjects" ItemsSource="{Binding MyList}"/>

That sets up your combobox to be bound to a list. So now we have to filter it down. So next I would use the KeyDown event to fire everytime the Combobox gets typed into.Then during that event you could capture the user's text, and try to find anything that matched that in the list, then set your list property equal to what was found..

private void cboObjects_KeyDown(object sender, KeyEventArgs e)
{
    string temp = ((ComboBox)sender).Text;

    var newList = MyList.Where(x => x.Name.Contains(temp));

    MyList = newList.ToList();
}

Now your list of people objects has been filtered! Although there are a few issues with doing it this way, like the fact that you now no longer have your original list. Another thing is, if you go this approach, your UI will not update unless its told to. So make use of the INotifyPropertyChanged interface. It will essentially fire an event anytime you update a property which then tells your UI to retrieve the value again.

Finally, As for your combobox not being editable try setting IsReadOnly = false, and IsEditable = true!

Upvotes: 0

Related Questions