首页 > 解决方案 > 尝试绑定到我的 ItemsControl 中的父视图模型绑定

问题描述

我希望在我的 ItemsControl 代码中绑定到我的 LDLTracks View 模型。但是,我的相对源绑定似乎没有正确绑定。

<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>

我想知道是不是因为上一级的父级实际上是我的 LineCoords,所以我必须再上一级吗?干杯。

标签: wpfmvvmbindingparent

解决方案


LDLTrackViewModel不是有效AncestorType的,因为它不是可视树中的元素。

您应该绑定到 parentContentPresenter的 parent ContentPresenter

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

推荐阅读