2009-07-14 84 views
165

我有一个窗口中包含的列表(见下文)。窗口的DataContext有两个属性,ItemsAllowItemCommandWPF数据绑定:如何访问“父”数据上下文?

如何获取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> 
+0

你可以进入调试器并逐步完成UI的构建点吗?如果是的话,你可以进入变量,并尝试钻取 – 2009-07-14 20:49:52

+0

简单的解决方案(这也适用于Windows 8商店/ Metro应用程序)在这里:[http://stackoverflow.com/questions/15366609/how-to-access-父母-的datacontext-在窗口-8-商店的应用程式/ 15419382#15419382](http://stackoverflow.com/questions/15366609/how-to-access-parents-datacontext-in-window-8-store-apps/15419382#15419382) – LMK 2013-06-13 03:18:55

回答

331

你可以尝试这样的事:

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

我用这个绑定到我的虚拟机上的一个ICommand,从一个StyleBox中的ListBoxItem上设置的ContextMenu绑定。工作很好,谢谢! – 2011-11-02 17:13:27

6

这也适用于在Silverlight 5(或许更早,以及,但我没有测试过)。我用这样的相对来源,它工作得很好。

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

17

这也将工作:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl}, 
          Path=DataContext.AllowItemCommand}" /> 

ListView将继承其DataContextWindow,所以它的使用在这一点上,太。
并且因为ListView,就像类似的控件(例如,Gridview,ListBox等)是ItemsControl的子类,所以这些控件的Binding将完美地工作。