Search code examples
c#wpfmvvmbindingviewmodel

I wish to bind to a list within a list in WPF


I have bound my ItemsSource in my ItemsControl to a list of ViewModels, called LDLTracks. Within an LDLTrack view model there is a list of coordinate objects I wish to bind to, however I'm not sure of the correct way to go about it.

I can do this via binding my canvas to the List of TrackViewModels and then within my

XAML:

<ItemsControl ItemsSource="{Binding LDLTracks}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <Canvas/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>

                    <ItemsControl.ItemTemplate>
                        <DataTemplate>

                            <Line  X1="{Binding X1}" Y1="{Binding Y1}" X2="{Binding X2}" Y2="{Binding Y2}" Stroke="{Binding LineColor}" StrokeThickness="5">
                                <Line.InputBindings>
                                    <MouseBinding Gesture="LeftClick" Command="{Binding FooCommand}"/>
                                </Line.InputBindings>
                            </Line>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>

I wish to replace the {Binding X1} With a List of Coordinates, so ideally it would be Coordinates.X1, as Coordinates would be a list, however when I try that the only property you can bind to is the Coordinates List count. Any ideas?


Solution

  • You could use an inner/nested ItemsControl that binds to the Coordinates list:

    <ItemsControl ItemsSource="{Binding LDLTracks}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding Coordinates}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Line X1="{Binding X1}" Y1="{Binding Y1}" X2="{Binding X2}" Y2="{Binding Y2}"
                                  Stroke="{Binding LineColor}" StrokeThickness="5">
                                <Line.InputBindings>
                                    <MouseBinding Gesture="LeftClick" Command="{Binding FooCommand}"/>
                                </Line.InputBindings>
                            </Line>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>