A.B.
A.B.

Reputation: 2470

Binding a nested List in XAML

My ViewModel looks like this:

public class MainViewModel : BaseViewModel
{
    public List<Paragraph> Paragraphs { get; set; }
    . . .
}

public class Paragraph
{
    public List<ParagraphElement> Elements; 
    . . .
}

And my XAML looks like this:

    <StackPanel Grid.Row="1">
        <ItemsControl ItemsSource="{Binding Paragraphs}">
            <ItemsControl ItemsSource="{Binding Elements}" ItemTemplate="{StaticResource ParagraphElements}" />
        </ItemsControl>
    </StackPanel>   

I get the following error: "XamlParseException"

and the Additional information: 'Add value to collection of type 'System.Windows.Controls.ItemCollection' threw an exception.'

How can I bind this nestes structure in XAML ?

Upvotes: 0

Views: 2004

Answers (1)

ASh
ASh

Reputation: 35680

you have to set ItemTemplate for outer ItemsControl. Exception is thrown because you set ItemsSource for outer ItemsControl and added an inner ItemsControl to Items collection at the same time

<StackPanel Grid.Row="1">
    <ItemsControl ItemsSource="{Binding Paragraphs}">
        <ItemsControl.ItemTemplate>
        <DataTemplate> 
          <Border BorderThickness="1" BorderBrush="Green">
             <ItemsControl ItemsSource="{Binding Elements}" 
                           ItemTemplate="{StaticResource ParagraphElements}" />
          </Border>
        </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</StackPanel>  

Upvotes: 1

Related Questions