Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 598
Gopinath Avatar asked Apr 15 '10 10:04

Gopinath


1 Answers

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);
        }            
    }
}
like image 159
Charlie Avatar answered Oct 03 '22 07:10

Charlie