Autocomplete combobox for WPF

后端 未结 7 1184
小蘑菇
小蘑菇 2020-12-09 00:05

I need an autocomplete combobox for WPF C#. I\'ve tried several approaches but nothing works. For example I\'ve tried a combobox:



        
7条回答
  •  旧时难觅i
    2020-12-09 00:30

    Here is the implementation that works for me:

    I check if the text has changed since the last time the filter was applied (to avoid filtering when a non-alphanumeric key is pressed).

    private string _textBeforeFilter;
    
    private void OnItemsControlKeyUp(object sender, KeyEventArgs e)
    {
        var arrowKey = e.Key >= Key.Left && e.Key <= Key.Down;
    
        // if arrow key (navigating) or the text hasn't changed, then a we don't need to filter
        if (arrowKey || ItemsControl.Text.EqualsIgnoreCase(_textBeforeFilter)) return;
    
        _textBeforeFilter = ItemsControl.Text;
    
        var textIsEmpty = string.IsNullOrWhiteSpace(ItemsControl.Text);
    
        var itemsViewOriginal = (CollectionView) CollectionViewSource.GetDefaultView(ItemsControl.ItemsSource);
        // if the text is empty, then we show everything, otherwise filter based on the text 
        itemsViewOriginal.Filter = o => textIsEmpty || ((string) o).ContainsIgnoreCase(ItemsControl.Text);
    }
    

    NOTE: EqualsIgnoreCase and ContainsIgnoreCase are extension methods:

    public static bool EqualsIgnoreCase(this string source, string value)
    {
        return source.Equals(value, StringComparison.OrdinalIgnoreCase);
    }
    
    public static bool ContainsIgnoreCase(this string source, string value)
    {
        return source.Contains(value, StringComparison.OrdinalIgnoreCase);
    }
    

提交回复
热议问题