【问题标题】:WPF AutoCompleteBox - How to restrict it choose only from the suggestion list?WPF AutoCompleteBox - 如何限制它仅从建议列表中选择?
【发布时间】:2010-04-15 10:46:15
【问题描述】:

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

有人可以建议我如何实施吗?任何示例代码表示赞赏。

【问题讨论】:

    标签: c# xaml wpftoolkit autocompletebox


    【解决方案1】:

    这就是我的做法。创建派生类并覆盖 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);
            }            
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以通过 Priview 按键事件来限制用户。我希望它会工作......

      【讨论】:

        【解决方案3】:

        如果你要将它数据绑定到一个属性,例如这样

        <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>
        

        如果输入的某些文本与 ItemsSource 中的任何内容都不匹配,则 SelectedItem 将等于 null。 在你的属性的 set 方法中,你可以不设置值,因为它是空的,并且属性将保持它的原始值。

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

        【讨论】:

          猜你喜欢
          • 2018-09-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-06
          • 2013-02-02
          • 2023-03-22
          • 2019-01-18
          相关资源
          最近更新 更多