Posts mit dem Label Filter werden angezeigt. Alle Posts anzeigen
Posts mit dem Label Filter werden angezeigt. Alle Posts anzeigen

Donnerstag, 12. April 2012

Binding multiple ComboBoxes to the same collection and using Filters

When multiple ComboBoxes bind to the same collection and the collection uses a Filtering, the items of all ComboBoxes get filtered. Not as expected only the one using the filter. If a ComboBox already has a value selected and another ComboBox uses a filter on the collection, the first ComboBox could lose its value because the SelectedItem is no longer contained in the displayed list.

This hapens because in WPF all Collections contain a default ICollectionView. This view can be retrieved with:

var view = CollectionViewSource.GetDefaultView(collection);


This can easily be handled if each ComboBox binds to a unique ICollectionView. It doesn't matter if the underlying Collection is the same as long as the ICollectionViews differ.


IList<ComboBoxExtDataObject> _dataObjects;
public IList<ComboBoxExtDataObject> DataObjects
{
    get
    {
        if (_dataObjects == null)
        {
            _dataObjects = new ObservableCollection<ComboBoxExtDataObject>();

            for (int i = 1; i <= 50; i++)
                _dataObjects.Add(new ComboBoxExtDataObject { Id = i, Name = "Name" + i });
        }
        return _dataObjects;
    }
}

ICollectionView _sources1;
public ICollectionView Sources1
{
    get
    {
        if (_sources1 == null)
        {
            var lst = new CollectionViewSource();
            lst.Source = _dataObjects;
            _sources1 = lst.View;
        }
        return _sources1;
    }
}

ICollectionView _sources2;
public ICollectionView Sources2
{
    get
    {
        if (_sources2 == null)
        {
            var lst = new CollectionViewSource();
            lst.Source = _dataObjects;
            _sources2 = lst.View;
        }
        return _sources2;
    }
}

In this case I bind the ComboBox1 to Sources1 and the ComboBox2 to Sources2. Now I can easily use the Filtering that I added to my ComboBox without changing the CollectionView of the other ComboBox.