开发者

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

开发者 https://www.devze.com 2022-12-27 12:58 出处:网络
I would like to res开发者_运维知识库trict WPF AutoCompleteBox (wpf toolkit control) to select an item only from the suggestion list. It should not allow users to type whatever they want.

I would like to res开发者_运维知识库trict 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.


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消