WPF组合框文本搜索使用包含而不是StartsWith

本文关键字:包含 StartsWith 组合 文本 搜索 WPF | 更新日期: 2023-09-27 18:02:41

我得到了一个ComboBox,有很多"客户"使用MultiBinding作为Text(例如"644 Pizza Place"),这从一开始就很好地搜索(CustomerNumber)。但是我如何匹配和选择,只要输入"Pizza Place"?

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

WPF组合框文本搜索使用包含而不是StartsWith

ComboBox使用TextSearch类查找项。您可以设置TextSearch。ComboBox上的TextPath依赖属性:

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

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

查找,没有太多细节,是通过以下方式完成的:组合框。在键入时调用textuupdated方法。这个方法调用TextSearch。FindMatchingPrefix查找匹配项。TextSearch。FindMatchingPrefix是使用string.StartsWith(..)调用的方法。

没有办法取代string.StartsWith()调用或TextSearch。FindMatchingPrefix调用其他东西。因此,如果您想将string.StartsWith()与自定义逻辑(如string.Contains)交换

,则必须编写自定义ComboBox类。

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

my xaml file:

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

my cs file:

//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(.....)};
    }
}

你可以看到可编辑的comboBox被绑定到字符串(SearchText)一旦出现TextChanged事件,下拉框就会显示出来,Two way绑定会更新该值。当ItemsSource进入set{};语法。

上面代码的要点