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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1127933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:43:50  来源:igfitidea点击:

WPF Databinding: How do I access the "parent" data context?

wpfdata-bindingdatacontext

提问by Jordan

I have a list (see below) contained in a window. The window's DataContexthas two properties, Itemsand AllowItemCommand.

我有一个包含在窗口中的列表(见下文)。窗口DataContext有两个属性,ItemsAllowItemCommand

How do I get the binding for the Hyperlink's Commandproperty needs to resolve against the window's DataContext?

我如何获得Hyperlink'sCommand属性的绑定需要解决窗口的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>

回答by flq

You could try something like this:

你可以尝试这样的事情:

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

回答by Kylo Ren

This will also work:

这也将起作用:

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

ListViewwill inherit its DataContextfrom Window, so it's available at this point, too.
And since ListView, just like similar controls (e. g. Gridview, ListBox, etc.), is a subclass of ItemsControl, the Bindingfor such controls will work perfectly.

ListView将继承其DataContextfrom Window,因此此时它也可用。
由于ListView就像类似的控件(例如GridviewListBox等)是 的子类ItemsControl,因此Binding此类控件将完美地工作。

回答by sangers

This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.

这也适用于 Silverlight 5(也许更早,但我还没有测试过)。我使用了这样的相对来源,效果很好。

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

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