Search code examples
wpfmvvmbindingparent

Attempting to bind to the parent view model binding in my ItemsControl


I wish to bind to my LDLTracks View model within my ItemsControl code. However, my relative source binding doesn't seem to bind correctly.

<ItemsControl ItemsSource="{Binding LDLTracks}">

                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <Canvas/>
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>

                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <ItemsControl ItemsSource="{Binding LineCoords}">

                                <ItemsControl.ItemTemplate>
                                    <DataTemplate>
                                        <Line  X1="{Binding X1}" Y1="{Binding Y1}" X2="{Binding X2}" Y2="{Binding Y2}" Stroke="Black" StrokeThickness="5">
                                            <Line.InputBindings>
                                                <MouseBinding Gesture="LeftClick" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type viewModel:LDLTrackViewModel}}, Path=FooCommand}"/>
                                            </Line.InputBindings>
                                        </Line>
                                    </DataTemplate>
                                </ItemsControl.ItemTemplate>

                            </ItemsControl>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>

                </ItemsControl>

I'm wondering whether it's because the parent 1 level up is actually my LineCoords, so would I have to go one level up again? Cheers.


Solution

  • LDLTrackViewModel is not a valid AncestorType since it's not an element in the visual tree.

    You should bind to the parent ContentPresenter's parent ContentPresenter:

    Command="{Binding DataContext.FooCommand, RelativeSource={RelativeSource AncestorType=ContentPresenter, AncestorLevel=2}}" />