Created
January 3, 2015 07:15
-
-
Save mariodivece/0bbade976aea8d416d52 to your computer and use it in GitHub Desktop.
Makes a WPF ComboBox Searchable via its items
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void MakeComboBoxSearchable(this ComboBox targetComboBox) | |
{ | |
targetComboBox.Loaded += (ls, le) => | |
{ | |
targetComboBox.Items.IsLiveFiltering = true; | |
var targetTextBox = targetComboBox.Template.FindName("PART_EditableTextBox", targetComboBox) as TextBox; | |
if (targetTextBox == null) return; | |
targetComboBox.IsEditable = true; | |
targetComboBox.IsTextSearchEnabled = false; | |
targetTextBox.Tag = "Selection"; | |
targetTextBox.PreviewKeyDown += (se, ev) => | |
{ | |
if (ev.Key == Key.Enter || ev.Key == Key.Return || ev.Key == Key.Tab) | |
return; | |
targetTextBox.Tag = "Typed"; | |
if (targetComboBox.SelectedItem != null) | |
{ | |
targetComboBox.SelectedItem = null; | |
targetComboBox.Text = string.Empty; | |
} | |
}; | |
targetTextBox.TextChanged += (se, ev) => | |
{ | |
var searchTerm = string.Empty; | |
if (string.IsNullOrWhiteSpace(targetTextBox.Text) == false && (string)targetTextBox.Tag == "Typed") | |
{ | |
targetComboBox.SelectedItem = null; | |
targetComboBox.IsDropDownOpen = true; | |
searchTerm = targetTextBox.Text.ToLowerInvariant(); | |
targetTextBox.Select(targetTextBox.Text.Length, 0); | |
targetComboBox.Items.Filter = (filterItem) => | |
{ | |
return filterItem.ToString().ToLowerInvariant().Contains(searchTerm); | |
}; | |
} | |
else | |
{ | |
targetComboBox.Items.Filter = (filterItem) => { return true; }; | |
} | |
targetComboBox.Items.Refresh(); | |
}; | |
targetComboBox.SelectionChanged += (se, ev) => | |
{ | |
if (targetComboBox.SelectedItem != null) | |
{ | |
targetTextBox.Tag = "Selection"; | |
targetComboBox.Items.Filter = (filterItem) => { return true; }; | |
targetComboBox.Items.Refresh(); | |
} | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried the above Extension, it fixed the SelectItem when DropDownOpen. But when searchingBox it doesn't get the binding value of Itemsources anymore.