WPF组合框文本搜索(包含搜索)

7
我该如何使用contains而不是StartsWith实现我的Combobox TextSearch?
<rf:ComboBox Grid.Row="1"
                         Grid.Column="5"
                         Width="200"
                         ItemsSource="{Binding Source={StaticResource AccountProvider}}"
                         DisplayMemberPath="Description"
                         SelectedValuePath="IndRekId"
                         IsEmptyItemVisible="True"
                         SelectedValue="{Binding Id, UpdateSourceTrigger=PropertyChanged}"
                         IsTextSearchEnabled="True"
                         TextSearch.TextPath="Description"
                         IsEditable="True"/>

搜索功能已经可以使用,但是我需要进行子字符串匹配。

1
据我所知,实现这一点的唯一方法是创建一个扩展ComboBox的控件,并添加您需要的功能。 - Adrian Fâciu
5个回答

6

我是一位有用的助手,可以为您进行翻译。

这里有一个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(.....)};
    }
}

您可以看到可编辑的comboBox绑定到字符串(SearchText)。一旦发生TextChanged事件,下拉框就会显示并且双向绑定会更新值。ItemsSource在cs文件中更改,同时进入set{};语法。
链接: https://gist.github.com/tonywump/82e66abaf71f715c4bd45a82fce14d80

3

这个示例看起来像是“文本搜索”。

在XAML文件中,您只需向组合框添加一个属性“TextContainSearch.Text”:

<ComboBox ItemsSource="{Binding Model.formListIntDeviceNumbers}" SelectedItem="{Binding Path=Model.selectedDeviceNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="DeviceNumber" IsEditable="True" c:TextContainSearch.Text="DeviceNumber">

我们需要在XAML文件的头部添加 using 语句:

并且我们应该在 XAML 文件的头部添加 using 语句:

xmlns:c="clr-namespace:Adaptive.Controls.Extension"

而在*.cs文件中的C#代码:

using System;
using System.Windows;
using System.Windows.Controls;
namespace Adaptive.Controls.Extension
{
 public sealed class TextContainSearch : DependencyObject {
        public static void SetText(DependencyObject element, string text) {
            var controlSearch = element as Control;
            if (controlSearch != null)
                controlSearch.KeyUp += (sender, e) =>
                {
                    if (sender is ComboBox){
                        var control = sender as ComboBox;
                        control.IsDropDownOpen = true;
                        var oldText = control.Text;
                        foreach(var itemFromSource in control.ItemsSource){
                            if (itemFromSource != null)
                            {
                                Object simpleType = itemFromSource.GetType().GetProperty(text).GetValue(itemFromSource, null);
                                String propertOfList = simpleType as string;
                                if (!string.IsNullOrEmpty(propertOfList) && propertOfList.Contains(control.Text))
                                {
                                    control.SelectedItem = itemFromSource;
                                    control.Items.MoveCurrentTo(itemFromSource);
                                    break;
                                }
                            }
                        }
                        control.Text = oldText;
                        TextBox txt = control.Template.FindName("PART_EditableTextBox", control) as TextBox;
                        if (txt != null)
                        {
                            txt.Select(txt.Text.Length, 0);
                        }
                    }
                };
        }
    }
}

这段代码片段中的模式叫什么?我知道附加属性并且大多数情况下使用它们来完成此代码片段所做的事情 - 注册控件的事件。虽然我从未见过这种方法,但我非常想知道您的方法是如何工作的。 - SnowballTwo
嗨@Evgenii, 但是在SetText(DependencyObject element,string text)中,“text”参数的值始终为“DeviceNumber”字符串。所以我的输入文本没有反映出来。 有什么原因吗? - Metallic Skeleton

3

试试这个:

 <ComboBox Padding="3,5" MinWidth="150" SelectedItem="{Binding NewBoxRequest}"
 ItemsSource="{Binding Requests}" DisplayMemberPath="SN" IsEditable="True"
 StaysOpenOnEdit="True"
 Text="{Binding SnFilter,UpdateSourceTrigger=PropertyChanged}">
 </ComboBox>

视图模型:

    private string snFilter;

    public string SnFilter
    {
        get { return snFilter; }
        set
        {
            snFilter = value;
            RaisePropertyChanged();
            RaisePropertyChanged(nameof(Requests));
        }
    }
    private List<Request> requests;

    public List<Request> Requests
    {
        get => string.IsNullOrEmpty(SnFilter) || requests.Any(r => r.SN == SnFilter)
            ? requests
            : requests.Where(r => r.SN.Contains(SnFilter)).ToList();
        set
        {
            requests = value;
            RaisePropertyChanged();
        }
    }

这是最简单的 - 我不确定 requests.Any() 条件是什么,我没有包含它,也没有注意到任何问题。 - PandaWood

2

1
我无法在我的C#系统中让“Set”语法运行起来,因此这里是对上面Wu答案的小调整(这是在自定义控件中):
 <ComboBox IsEditable="True" 
      IsTextSearchEnabled="false" 
      ItemsSource="{Binding pData, RelativeSource = {RelativeSource TemplatedParent}}"  
      DisplayMemberPath="description" 
      Text="{Binding SearchText , RelativeSource = {RelativeSource TemplatedParent}, 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>

在自定义控件中:
private async void _Loaded(object sender, RoutedEventArgs e)
        {
            var n = await InitializeLabTests;

            allTests = new ObservableCollection<CommonProcedure>(n);
            pData = new ObservableCollection<CommonProcedure>(n);
        }

//ItemsSource - pData
        //There is a string attribute - wTitle included in the fooClass (DisplayMemberPath)
        private ObservableCollection<CommonProcedure> __pData;
        public ObservableCollection<CommonProcedure> pData
        {
            get { return __pData; }
            set { __pData = value; RaisePropertyChanged(); }
        }

        private string _SearchText;
        public string SearchText
        {
            get { return _SearchText; }
            set
            {
                _SearchText = value; RaisePropertyChanged();

                //Update your ItemsSource here with Linq
                pData = new ObservableCollection<CommonProcedure>
               (
                    allTests.Where(q => q.description.Contains(SearchText))
               );
            }
        }

唯一的显著区别在于SearchText设置器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接