Search code examples
c#xamlwpftoolkitautocompletebox

WPF AutoCompleteBox - How to restrict it choose only from the suggestion list?


I would like to restrict WPF AutoCompleteBox (wpf toolkit control) to select an item only from the suggestion list. It should not allow users to type whatever they want.

Can someone suggest me how to implement this? Any sample code is appreciated.


Solution

  • Here's how I did it. Create a derived class and override OnPreviewTextInput. Set your collection to the control's ItemsSource property and it should work nicely.

    public class CurrencySelectorTextBox : AutoCompleteBox
    {    
        protected override void OnPreviewTextInput(TextCompositionEventArgs e)
        {            
            var currencies = this.ItemsSource as IEnumerable<string>;
            if (currencies == null)
            {
                return;
            }
    
            if (!currencies.Any(x => x.StartsWith(this.Text + e.Text, true, CultureInfo.CurrentCulture))
            {
                e.Handled = true;
            }
            else
            {
                base.OnPreviewTextInput(e);
            }            
        }
    }