WPF AutoCompleteBox - 如何限制它只从建议列表中选择?

Gop*_*ath 6 c# xaml wpftoolkit autocompletebox

我想限制WPF AutoCompleteBox(wpf工具包控件)只从建议列表中选择一个项目.它不应该允许用户键入他们想要的任何内容.

有人可以建议我如何实现这个?任何示例代码都表示赞赏.

Cha*_*lie 3

我是这样做的。创建派生类并重写 OnPreviewTextInput。将您的集合设置为控件的 ItemsSource 属性,它应该可以正常工作。

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);
        }            
    }
}
Run Code Online (Sandbox Code Playgroud)