Mike
Mike

Reputation: 3284

Rendering Collection of collections - ItemsControl

I have an object model like below:

public class ViewModel
{
 public List<Group> Groups{ get; set; }
}

public class Group
{
    public string Name { get; set; }
    public List<Contact> Contacts { get; set; }
}

public class Contact
{
    public string Name { get; set; }
    public bool IsOnline { get; set; }
}

and I'm binding the groups to an itemscontrol like this:

  <ItemsControl  ItemsSource="{Binding Path=Groups}"
       ItemTemplate="{StaticResource GroupTemplate}" >
    </ItemsControl>

and I have datatemplate for rendering them.

       <DataTemplate x:Key="GroupTemplate" DataType="{x:Type Group}">
       </DataTemplate>
 <DataTemplate x:Key="ContactTemplate" DataType="{x:Type Contact}">
<StackPanel>
<TextBlock Text="{Binding Name}"/>
</StackPanle>
       </DataTemplate>

How can I get the contacts displayed inside the items control? The contacts is a collection inside each group and my viewmodel has a collection of groups. To complicate it a bit further, I have different datatemplates for different contacts, and I should be using a datatemplateselector for choosing the appropriate contact template. Also please note, I have nothing to display in the group template, and I only need to show Contacts.

Thanks, -Mike

Upvotes: 1

Views: 414

Answers (1)

Adrian F&#226;ciu
Adrian F&#226;ciu

Reputation: 12552

Use another ItemsControl in the first template:

<DataTemplate x:Key="GroupTemplate" DataType="{x:Type my:Group}">
    <ItemsControl ItemsSource="{Binding Contacts}">
        <ItemsControl.ItemTemplate>
            <DataTemplate DataType="{x:Type my:Contact}">
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</DataTemplate>

And with a template selector:

<DataTemplate x:Key="GroupTemplate" DataType="{x:Type my:Group}">
  <ItemsControl ItemsSource="{Binding Contacts}"
                ItemTemplateSelector="{StaticResource yourContactItemSelector}"/>
 </DataTemplate>

Upvotes: 1

Related Questions