WPF数据绑定:如何访问“父级”数据上下文?

236

我有一个包含在窗口中的列表(请参见下面)。 窗口的 DataContext 具有两个属性:ItemsAllowItemCommand

我该怎么做才能使 HyperlinkCommand 属性的绑定解析为窗口的 DataContext

<ListView ItemsSource="{Binding Items}">
  <ListView.View>
    <GridView>
      <GridViewColumn Header="Action">
        <GridViewColumn.CellTemplate>
          <DataTemplate>
            <StackPanel>
              <TextBlock>

                <!-- this binding is not working -->
                <Hyperlink Command="{Binding AllowItemCommand}"
                           CommandParameter="{Binding .}">
                    <TextBlock Text="Allow" />
                </Hyperlink>

              </TextBlock>
            </StackPanel>
          </DataTemplate>
        </GridViewColumn.CellTemplate>
      </GridViewColumn>
    </GridView>
  </ListView.View>
</ListView>

你能进入调试器,逐步执行代码直到 UI 构建时吗?如果可以,你能进入变量并尝试查看上层内容吗? - ist_lion
简单的解决方案(也适用于Windows 8 Store/Metro应用程序)在这里:https://dev59.com/OWUp5IYBdhLWcg3wTGTe#15419382 - LMK
3个回答

463

你可以尝试像这样做:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...

4
我使用这个方法将上下文菜单设置到样式中的ListBoxItem上,并将其绑定到VM上的ICommand。效果很好,谢谢! - Wil P
1
在Windows 8应用程序中,如何做到这一点?我使用了“ElementName = ...”使其工作,但它会泄漏DataContext。 - Joris Weimar
很遗憾对我没用,因为父级在不同的文件中。 - Thomas
@Thomas6767,希望你已经解决了问题,能否请你分享一下你的代码。 - Mohammed Abrar Ahmed
@MohdAbrarAhmed,可能需要一些时间,但我会在这个周末找到它。 - Thomas
1
谢谢!我之前一直在混淆相对绑定,因为我以为它会给我祖先的DataContext,而不是祖先本身。添加DataContext.<MyProperty>解决了问题 :) - DrEsperanto

53
这也会起作用:
<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />

ListView 会从 Window 继承其 DataContext,因此在此时也可以使用。
而且,由于 ListView 和类似控件(例如 GridViewListBox 等)都是 ItemsControl 的子类,因此这些控件的 Binding 将完美地工作。


35
看着这张海报和编辑,我觉得这篇帖子很有趣... :D - Jack Frost
1
@JackFrost 如果Yoda再次干扰Kylo的工作,Kylo就要杀了Yoda。 :P - Kylo Ren
2
不行,他不能。尤达现在已经与原力合为一体了。嘿嘿嘿。 - Jack Frost

10

这也适用于Silverlight 5(也许更早,但我没有测试过)。我像这样使用相对源,它可以正常工作。

RelativeSource = "{RelativeSource Mode = FindAncestor,AncestorType = telerik:RadGridView}"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接