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;
}

4.38
8

                                    <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>

4.38 (8 Votes)
0
Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source