3
votes

I have a ComboBox in my WPF App, that I want to enter Text in, which is used to update the Content (Items) of the ComboBox.

Whenever I enter a character, I want the updated Items to show. So I set IsDropDownOpen = true;, but this causes the Text which was entered to be selected.

The result is: I type 1 char, the ComboBox DropDown is opened (and shows new Items), the char gets selected. I type a second char and it replaces the first one, because it was selected (duh)!

How can I deselect all Text in the ComboBox? I obviously want to type more than 1 char whithout having to click on the ComboBox again to deselect all text...

Code:

//MainWindow.xaml
<ComboBox x:Name="comboBoxItemID" HorizontalAlignment="Left" Height="38"
 VerticalAlignment="Top" Width="300" Canvas.Left="197" FontSize="21.333"
 IsEnabled="True" KeyUp="comboBoxItemID_KeyUp" IsEditable="True"/>

//comboBoxItemID_KeyUp()
List<InventorySearchResult> Items = Invent.SearchArticle(this.comboBoxItemID.Text); //Get new Data
comboBoxItemID.ItemsSource = Items;         //Update comboBox Data
comboBoxItemID.DisplayMemberPath = "Name";
comboBoxItemID.IsDropDownOpen = true;
1
Do you have to constantly change the itemssource, or can you have all the data in it to begin with? If the latter is the case, you can just do that and the search is built into the comboboxGordon Allocman
It changes, based on what is typed in. Invent.SearchArticle() actually performs a SQL Query, the returned List<InventorySearchResult> is a list of Rows returned by that query. Or should I declare a List, that that as ItemsSource once, and only change that list's contents?NoMad
I don't know if changing the contents would make a difference, it might. If you try it, switch to an observable collection otherwise your ui won't update and you will likely get exceptions thrownGordon Allocman
It probably isn't the best idea to query a database everytime a single key is pressed thoughGordon Allocman
Re-innovating autocomplete?Sinatr

1 Answers

3
votes

To deselect all Text from a ComboBox, first get the TextBox Element:

TextBox tb = (TextBox)comboBoxItemID.Template.FindName("PART_EditableTextBox", comboBoxItemID);

(source: How to get ComboBox.SelectedText in WPF )

Then use the TextBox method Select(int start, int length) to set the selection, e.g.

tb.Select(tb.Text.Length, 0);

(source: Deselect text in a textbox )

Finally, disable the IsTextSearchEnabled property. I haven't done much testing to find out why exactly this has to be disabled, but I guess in my case it conflicts with the way I update the Items and then deselect the Text.