Alan Coromano
Alan Coromano

Reputation: 26018

Changing the data source of ListView dynamically

I have a ListView and data source for it which it populate from the Internet. Once it's populate it should remain static unless a user makes a new http request. Now I have something like this:

class MyDataItem {
  public int Field1 { get; set; }
  public string Field2 { get; set; }
}

class Window1: Window {
  private List<MyDataItem> dataSource = new ...

  void sendHttpRequest(...) {
    dataSource = getFromInternet();
    myListView.ItemsSource = dataSource ;
  }
}

And say, I have a checkbox. When I click on it, I want to filter the data by some filter.

//.........
// the checkbox is checked
var filterDataSource = dataSource.Where(....)

How can I make my ListView update its data with data source to be filterDataSource? And then when the checkbox is unchecked again, how will I make it show the initial data source?

Upvotes: 1

Views: 313

Answers (1)

Absolom
Absolom

Reputation: 1389

Here is some code to help you. Please note that this was not tested nor compiled but it can give you some hints on how to handle your case. The trick is to use a CollectionViewSource that lets you filter your data.

class Window1: Window {
    private readonly ObservableCollection<MyDataItem> _children;
    private readonly CollectionViewSource _viewSource;

    public Window1()
    {
        // ... 

        _children = new ObservableCollection<MyDataItem>();
        _viewSource = new CollectionViewSource
        {
            Source = _children
        };
        myListView.ItemsSource = _viewSource;

        // ...
    }

    // This method needs to be called when your checkbox state is modified.
    // "filter = null" means no filter
    public void ApplyFilter(Func<MyDataItem, bool> filter)
    {
        if (_viewSource.View.CanFilter)
        {
            _viewSource.View.Filter = (filter == null) ? (o => true): (o => filter((MyDataItem) o));
        }
    }

Upvotes: 1

Related Questions