Skip to content

Instantly share code, notes, and snippets.

@mariodivece
Created January 3, 2015 07:15
Show Gist options
  • Select an option

  • Save mariodivece/0bbade976aea8d416d52 to your computer and use it in GitHub Desktop.

Select an option

Save mariodivece/0bbade976aea8d416d52 to your computer and use it in GitHub Desktop.
Makes a WPF ComboBox Searchable via its items
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();
}
};
};
}
@devMagics

devMagics commented Apr 14, 2017

Copy link
Copy Markdown

what MaxValue means ?

@Lerosbeef

Copy link
Copy Markdown

This is great! I replaced:
targetTextBox.CaretIndex = MaxValue; targetComboBox.IsDropDownOpen = true;

With:
targetComboBox.IsDropDownOpen = true; targetTextBox.SelectionStart = targetTextBox.Text.Length;

@vogelor

vogelor commented Feb 6, 2019

Copy link
Copy Markdown

what MaxValue means ?

i know this question is old. But: MaxValue = int.MaxValue

@quoctrunggol

Copy link
Copy Markdown

I tried the above Extension, it fixed the SelectItem when DropDownOpen. But when searchingBox it doesn't get the binding value of Itemsources anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment