Gopinath
Gopinath

Reputation: 1858

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.

Upvotes: 6

Views: 3611

Answers (3)

Michael
Michael

Reputation: 663

If you are databinding it to a property, like this for an example

<sdk:AutoCompleteBox ItemsSource="{Binding Sites, Source={StaticResource VmSchedulel}}" ValueMemberPath="SiteName"
                                             SelectedItem="{Binding Site, Mode=TwoWay}" FilterMode="ContainsOrdinal">
                            <sdk:AutoCompleteBox.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding SiteName}"/>
                                </DataTemplate>
                            </sdk:AutoCompleteBox.ItemTemplate>
                        </sdk:AutoCompleteBox>

If some text is entered which doesn't match anything in the ItemsSource, the SelectedItem will be equal to null. In the set method of your property, you can just not set the value because it's null, and the Property will keep it's original value.

 set
        {
            if (value != null)
            {
                BaseRecord.SiteID = value.ID;
                PropChanged("Site");
            }
        }

Upvotes: 1

Charlie
Charlie

Reputation: 10307

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

Upvotes: 3

Zubair
Zubair

Reputation: 11

You can restrict user by Priview key down event. I hope it will work...

Upvotes: 1

Related Questions