简单的WPF组合框过滤器 [英] Simple WPF combobox filter

查看:961
本文介绍了简单的WPF组合框过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已搜查谷歌一个简单的解决这个,但没有运气。我有一个标准的WPF组合框我只是想能够过滤根据第一2个或3个字母一个用户类型时,组合框具有焦点显示的列表中。我尝试了一些编码包括一些兰巴表达式,但错误System.NotSupportedException不断得到扔在其中指定了combobox.Items.Filter的路线。我没有使用MVVM和只想可供用户使用这个简单的功能。请帮忙!附: IsEditable,IsTextSearchEnabled和StaysOpenOnEdit属性被设置为true,但尚未达到预期的功能。

I have searched Google for a simple solution to this but no luck. I have a standard WPF combo box which I would simply like to be able to filter the list displayed according to the first 2 or 3 letters a users types when the combo box has focus. I tried some coding including some lamba expressions but the error "System.NotSupportedException" keeps getting thrown on the line where "combobox.Items.Filter" is specified. I'm not using MVVM and would just like this simple functionality available for the user. Please help! P.S. IsEditable, IsTextSearchEnabled and StaysOpenOnEdit properties are set to true but the desired functionality is not yet achieved.

推荐答案

我已经开发了一个示例应用程序。我用字符串作为记录项,您可以使用自己的实体做到这一点。 。Backspace键也正常工作

I have developed a sample application. I have used string as record item, you can do it using your own entity. Backspace also works properly.

 public class FilterViewModel
    {
        public IEnumerable<string> DataSource { get; set; }       

        public FilterViewModel()
        {
            DataSource = new[] { "india", "usa", "uk", "indonesia" };           
        }
    }

public partial class WinFilter : Window
    {
          public WinFilter()
          {
             InitializeComponent();

             FilterViewModel vm = new FilterViewModel();
             this.DataContext = vm;
          }

          private void Cmb_KeyUp(object sender, KeyEventArgs e)
          {
              CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(Cmb.ItemsSource);

              itemsViewOriginal.Filter = ((o) =>
              {
                  if (String.IsNullOrEmpty(Cmb.Text)) return true;
                  else
                  {
                     if (((string)o).Contains(Cmb.Text)) return true;
                     else return false;
                  }
              });

             itemsViewOriginal.Refresh();

             // if datasource is a DataView, then apply RowFilter as below and replace above logic with below one
             /* 
              DataView view = (DataView) Cmb.ItemsSource; 
              view.RowFilter = ("Name like '*" + Cmb.Text + "*'"); 
             */
          }
     }



XAML

XAML

<ComboBox x:Name="Cmb" IsTextSearchEnabled="False" IsEditable="True" ItemsSource="{Binding DataSource}" Width="120"  IsDropDownOpen="True" StaysOpenOnEdit="True" KeyUp="Cmb_KeyUp" />

这篇关于简单的WPF组合框过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆