Filter a DataGrid in WPF

后端 未结 5 2091
庸人自扰
庸人自扰 2020-12-05 08:21

I load a lists of objects in a datagrid with this:

dataGrid1.Items.Add(model);

The model become data from a database. It has a

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 09:01

    This is a simple implementation of using the Filter property of ICollectionView. Suppose your XAML contains this:

    
    

    Then in the constructor you can get the default view for your data where you can set the filter predicate which will be executed for every item of your collection. The CollectionView won't know when it should update the collection, so you have to call Refresh when the user clicks the search button.

    private ICollectionView defaultView;
    
    public MainWindow()
    {
        InitializeComponent();
    
        string[] items = new string[]
        {
            "Asdf",
            "qwer",
            "sdfg",
            "wert",
        };
    
        this.defaultView = CollectionViewSource.GetDefaultView(items);
        this.defaultView.Filter =
            w => ((string)w).Contains(SearchTextBox.Text);
    
        MyDataGrid.ItemsSource = this.defaultView;
    }
    
    private void SearchButton_OnClick(object sender, RoutedEventArgs e)
    {
        this.defaultView.Refresh();
    }
    

    At this url you can find a more detailed description of CollectionViews: http://wpftutorial.net/DataViews.html

提交回复
热议问题