wpf combobox filter as you type code example
Example 1: wpf combobox filter as you type
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" SelectedValuePath="Content" SelectedValue="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Text}" VerticalAlignment="Top" Width="120" Margin="121,100,0,0" IsEditable="True" KeyUp="comboBox_KeyUp" IsTextSearchEnabled="False">
<ComboBoxItem Content="apple"/>
<ComboBoxItem Content="banana"/>
<ComboBoxItem Content="grape"/>
<ComboBoxItem Content="lemon"/>
<ComboBoxItem Content="strawberry"/>
</ComboBox>
Example 2: wpf combobox filter as you type
private void comboBox_KeyUp(object sender, KeyEventArgs e)
{
var combobox = (ComboBox)sender;
var ctb = combobox.Template.FindName("PART_EditableTextBox", combobox) as TextBox;
if (ctb == null) return;
if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) || Keyboard.Modifiers.HasFlag(ModifierKeys.Control) || Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
return;
var caretPos = ctb.CaretIndex;
combobox.IsDropDownOpen = true;
CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(combobox.Items);
itemsViewOriginal.Filter = ((o) =>
{
if (String.IsNullOrEmpty(combobox.Text))
{
return true;
}
else
{
if (((ComboBoxItem)o).Content.ToString().StartsWith(combobox.Text, true, null))
{
return true;
}
else
{
return false;
}
}
});
itemsViewOriginal.Refresh();
ctb.CaretIndex = caretPos;
}