WPF数据绑定:如何访问"父"数据上下文?

Jor*_*dan 202 data-binding wpf datacontext

我有一个窗口中包含的列表(见下文).窗口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>
Run Code Online (Sandbox Code Playgroud)

flq*_*flq 398

你可以尝试这样的事情:

...Binding="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...
Run Code Online (Sandbox Code Playgroud)

  • 泄漏是什么意思? (3认同)
  • 我使用它从一个Style中的ListBoxItem上设置的ContextMenu绑定到我的VM上的ICommand.工作得很好,谢谢! (2认同)

Kyl*_*Ren 28

这也有效:

<Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType=ItemsControl},
                             Path=DataContext.AllowItemCommand}" />
Run Code Online (Sandbox Code Playgroud)

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

  • (看海报和编辑)我发现这篇文章很有趣......:D (9认同)
  • 不,他不能。尤达现在是原力中的一员。呵呵呵呵 (2认同)

小智 7

这也适用于Silverlight 5(也许更早,但我还没有测试过).我使用了这样的相对来源,它工作得很好.

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