Filter a DataGrid on a Text box

前端 未结 4 1955
挽巷
挽巷 2020-12-03 01:12

I search an example or sample to filter the WPF DataGrid column elements by a textbox.

\"alt

S

相关标签:
4条回答
  • 2020-12-03 01:59

    I have written my own FilterDataGrid Control, it's much more flexible than the ones provided on CodeProject or elsewhere. I can neither post the full code here, nor can I publish it.

    But: Since your datasource is most likely wrapped into a ICollectionView, you can do something like this:

        public void ApplyFilters()
        {
            ICollectionView view = CollectionViewSource.GetDefaultView(ItemsSource);
            if (view != null)
            {
                view.Filter = FilterPredicate; 
            }
        }
    
        private bool FilterPredicate(object item)
        {
            var yourBoundItemOrRow = item as BoundItemType;
    
            return aFilterObject.Matches(yourBoundItemOrRow);
        }
    

    You can implement any filter logic easily based on this concept. Even very, very powerful filters. Note: I have those methods in my own class derived from datagrid. They can be adapted to work outside of the grid, too, for example in a UserControl

    0 讨论(0)
  • 2020-12-03 02:00

    You can filter the Items in the DataGrid by binding it to an ICollectionView that supports filtering.

    Details here for .NET 4. The process is the same for .NET 4.5, but it seems the documentation has been lost. There's a small mention to it here under the "Grouping, Sorting, and Filtering" heading.

    edit: at the time this was originally written, the WPF toolkit had not been abandoned by Microsoft. The controls that used to be part of it are now in the framework, and the toolkit was alive and doing well here

    0 讨论(0)
  • 2020-12-03 02:06

    I have seen at various sites much ado about this matter...

    To filter the latter being a datagrid using a datatable as the source, which is quite common to make the code below:

    DataTable dt = new DataTable("Table1");
    
    //fill your datatable...
    
    //after fill...
    dataGrid1.DataContext = dt;
    IBindingListView blv = dt.DefaultView;
    blv.Filter = "NAME = 'MOISES'";
    
    0 讨论(0)
  • 2020-12-03 02:07

    There are several solutions, but in my opinion, the best solutions are the ones which uses only DataGrid styles without inventing a new inherited DataGird type. The followings are the best I found:

    • Option 1: which I personally use: Automatic WPF Toolkit DataGrid Filtering
    • Option 2: Auto-filter for Microsoft WPF DataGrid
    0 讨论(0)
提交回复
热议问题