Simple WPF combobox filter

前端 未结 2 607
Happy的楠姐
Happy的楠姐 2020-12-09 23:38

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

2条回答
  •  余生分开走
    2020-12-10 00:28

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

    
    

提交回复
热议问题