0

I'm trying to use a composite collection as the ItemsSource for an ItemsControl. The ItemsControl should then display a different control based on the type of object in the composite collection.

As per this question:

How do you bind a CollectionContainer to a collection in a view model?

I see that I can't bind a composite collection directly as the ItemsSource, like this:

ItemsSource="{Binding CombinedCollection}"

So I've created the composite collection in the ItemsControl Resources:

<ItemsControl.Resources>
    <CompositeCollection x:Key="cmpcol">
        <CollectionContainer Collection="{Binding TimeSlots}"/>
        <CollectionContainer Collection="{Binding Items}"/>
    </CompositeCollection>
    <DataTemplate DataType="{x:Type tg:TimeSlot}">
        <tgvw:TimeSlotRect/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type tg:Item}">
        <TextBox></TextBox>
    </DataTemplate>         
</ItemsControl.Resources>

How do I now set the composite collection as the ItemsSource? I can't seem to get the syntax. I presume it's something like:

<ItemsControl.ItemsSource>
   <!--Something Here-->
</ItemsControl.ItemsSource>

As an aside, this answer here https://stackoverflow.com/a/5473443/2591770 manages to bind to a collection in the viewmodel directly - but I can't tell what the 'Data' object is in the example.

Community
  • 1
  • 1
jidl
  • 195
  • 1
  • 2
  • 19

2 Answers2

0

Create a collection in View Model with the type of object. and add your Composite Collection Inside that. Then bind the List to the Items control Item source.

  • In the viewmodel should that be a ObservableCollection, Collection or List? – jidl Feb 26 '15 at 08:44
  • ObservableCollection it would be nice. It will raise automatically. –  Feb 26 '15 at 08:58
  • Doesn't seem to work I've created the oc and added the composite collection. Maybe the problems in the XAML? – jidl Feb 26 '15 at 09:40
0

Solved.

It turns out, in the viewmodel:

CompositeCollection CombinedCollection = new CompositeCollection();

is not the same as:

CombinedCollection = new CompositeCollection();

I used the latter and it worked fine with:

ItemsSource="{Binding CombinedCollection}"

Rookie mistake!

jidl
  • 195
  • 1
  • 2
  • 19