rtkite
rtkite

Reputation: 47

ICollectionView within CompositeCollection

I using a CompositeCollection defined in my ViewModel to render shapes (of various types) to a Canvas. I've created several ICollectionView's from my underlying data.

// ViewModel
ICollectionView view1 = new CollectionViewSource() { Source = ObservableCollectionA }.View;
view1.Filter = ...

I then create a CompositeCollection to bind in xaml:

_CompositeCollection = new CompositeCollection();
var container = new CollectionContainer() { Collection = viewModel.view1 };
_CompositeCollection.Add(container);

In the view, I bind _CompositeCollection container to an ItemsControl with an ItemsPanelTemplate of Canvas.

Nothing is added to the Canvas. If I remove the ICollectionView layer from the ViewModel and just use the ObservableCollection directly in the CollectionContainer.Collection it works fine:

var container = new CollectionContainer() { Collection = viewModel.ObservableCollectionA };

I don't want to expose the ObservableCollection directly, which I think is consistent with the whole MVVM paradigm.

Its seems like CompositeCollection isn't working correctly; how do I merge several ICollectionViews into one collection for binding to a single ItemsControl? Or perhaps there is a better structure to use?

I am using C# 4.0.

Upvotes: 1

Views: 449

Answers (1)

XAMlMAX
XAMlMAX

Reputation: 2363

CollectionViewSource should be part of UI as you need the PresentationFramework.dll to use it.
As for the structure I usually have this:
in xaml:

<CollectionViewSource Source="{Binding CmbList}" x:Key="cmbList"></CollectionViewSource>
<CollectionViewSource Source="{Binding Items}" x:Key="items"></CollectionViewSource><!-- this goes into your Resources tag

<ComboBox>
    <ComboBox.ItemsSource><!-- in here we are using multiple types of collections and objects
        <CompositeCollection>
            <CollectionContainer Collection="{Binding Source={StaticResource items}}"></CollectionContainer>
            <sys:String>Newly added item</sys:String>
            <CollectionContainer Collection="{Binding Source={StaticResource cmbList}}"></CollectionContainer>
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>  

where xmlns:sys="clr-namespace:System;assembly=mscorlib"
And my ViewModel has this as the collections defined:

private string[] _items;

public string[] Items
{
    get { return _items; }
    set { _items = value; OnPropertyChanged("Items"); }
}
private List<int> _cmbList;

public List<int> CmbList
{
    get { return _cmbList; }
    set { _cmbList = value; OnPropertyChanged("CmbList"); }
}

As you will see this will display the 2 very different types of collections plus additional item that we created.

Upvotes: 1

Related Questions