自引用xaml文件

时间:2010-12-17 12:17:54

标签: wpf xaml binding

我在WPF应用程序中使用Model View ViewModel模式。 我视图的DataContext设置为ViewModel。

我的视图中有一个ListView,它有一个ContextMenu,其中一个MenuItem需要绑定到Command,CommandParameter是ListView本身。

现在我的问题是,我不知道如何引用ListView。也许代码片段更容易理解:

<ListView 
            Name="lvTestList"
            ItemsSource="{Binding Path=TestList.Items}">

            <!-- Context Menu of the selected test -->
            <ListView.ContextMenu>
                <ContextMenu>
                    <MenuItem
                        Header="Remove from List"
                        IsEnabled="{Binding IsATestSelected}" 
                        Command="{Binding RemoveTestFromTestListCommand}" 
                        CommandParameter="{Binding ElementName=lvTestList}"/>
                </ContextMenu>
            </ListView.ContextMenu>

            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding TestName}"/>
                    <GridViewColumn Header="Package" DisplayMemberBinding="{Binding PackageName}"/>
                    <GridViewColumn Header="Expected Duration" DisplayMemberBinding="{Binding ExpectedDuration}"/>
                </GridView>
            </ListView.View>
        </ListView>

有问题的一句话是:

CommandParameter="{Binding ElementName=lvTestList}"/>

通常情况下,这会有效。但是,如果整个类的DataContext发生更改,它只会将null作为参数传递。

有谁知道如何保持对当前xaml文档的引用?或者如何直接与ListView“lvTestList”“对话”?

祝愿并感谢您的帮助, 基督教

2 个答案:

答案 0 :(得分:1)

您可以通过reltivesource FindAncestor绑定获取对ListView的引用:

{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}

您希望将ListView作为参数传递给命令似乎有点奇怪,也许您应该使用:

{Binding Path=DataContext.Something, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}

将路径设置为DataContext,然后您就可以绑定父视图模型。

希望有所帮助, 科林E.

答案 1 :(得分:1)

使用Self Binding

CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Parent.PlacementTarget.Name}"

将CommandParameter的值设置为“lvTestList”。

您还可以使用Ancestor Binding

CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget.Name}"

在这些示例中,PlacementTarget将是一个打开ContextMenu的控件。在您的情况下,它将是ListView