【问题标题】:WPF ComboBox TextSearch using Contains instead of StartsWithWPF ComboBox TextSearch 使用 Contains 而不是 StartsWith
【发布时间】:2017-01-24 02:12:08
【问题描述】:

我得到了一个ComboBox,其中有很多“客户”使用MultiBinding 作为Text(例如“644 Pizza Place”),这从一开始就很好地搜索(客户编号)。但是如何通过输入“Pizza Place”使其匹配和选择?

<MultiBinding StringFormat="{}{0} {1}">
    <Binding Path="CustomerNumber" />
    <Binding Path="CustomerName" />
</MultiBinding>

【问题讨论】:

    标签: c# wpf combobox


    【解决方案1】:

    ComboBox 使用TextSearch class 进行项目查找。您可以在 ComboBox 上设置 TextSearch.TextPath 依赖属性:

        <ComboBox Name="cbCustomers" TextSearch.TextPath="CustomerName">...</ComboBox>
    

    这将允许您按 CustomerName 进行匹配,但您将失去按 CustomerNumber 的匹配。

    查找,没有太多细节,是通过以下方式完成的: ComboBox.TextUpdated 方法在您键入时被调用。此方法调用 TextSearch.FindMatchingPrefix 来查找匹配项。 TextSearch.FindMatchingPrefix 是使用 string.StartsWith(..) 调用的方法。

    无法用其他方法替换 string.StartsWith() 调用或 TextSearch.FindMatchingPrefix 调用。因此,如果您想将 string.StartsWith() 与您的自定义逻辑(如 string.Contains)交换,看起来您必须编写自定义 ComboBox 类

    【讨论】:

      【解决方案2】:

      这里我在 MVVM 框架中有一个替代方案。

      我的 xaml 文件:

      <ComboBox Name="cmbContains" IsEditable="True" IsTextSearchEnabled="false" ItemsSource="{Binding pData}"  DisplayMemberPath="wTitle" Text="{Binding SearchText ,Mode=TwoWay}"  >
        <ComboBox.Triggers>
            <EventTrigger RoutedEvent="TextBoxBase.TextChanged">
                <BeginStoryboard>
                    <Storyboard>
                        <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsDropDownOpen">
                            <DiscreteBooleanKeyFrame Value="True" KeyTime="0:0:0"/>
                        </BooleanAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </ComboBox.Triggers>
      </ComboBox>
      

      我的cs文件:

      //ItemsSource - pData
      //There is a string attribute - wTitle included in the fooClass (DisplayMemberPath)
      private ObservableCollection<fooClass> __pData;
      public ObservableCollection<fooClass> pData {
          get { return __pData; }
          set { Set(() => pData, ref __pData, value);
              RaisePropertyChanged("pData");
          }
      }
      
      private string _SearchText;
      public string SearchText {
          get { return this._SearchText; }
          set {
              this._SearchText = value;
              RaisePropertyChanged("SearchText");
      
              //Update your ItemsSource here with Linq
              pData = new ObservableCollection<fooClass>{pData.ToList().Where(.....)};
          }
      }
      

      您可以看到可编辑的组合框正在绑定到字符串(SearchText) 一旦出现 TextChanged 事件,就会显示下拉菜单,并且双向绑定会更新该值。 在进入 set{} 时,cs 文件中的 ItemsSource 发生了变化;语法。

      A gist with the code above

      【讨论】:

      猜你喜欢
      • 2010-09-16
      • 1970-01-01
      • 2021-01-07
      • 2012-03-18
      • 1970-01-01
      • 2011-03-24
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多