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
WPF Databinding: How do I access the "parent" data context?
提问by Jordan
I have a list (see below) contained in a window. The window's DataContext
has two properties, Items
and AllowItemCommand
.
我有一个包含在窗口中的列表(见下文)。窗口DataContext
有两个属性,Items
和AllowItemCommand
。
How do I get the binding for the Hyperlink
's Command
property 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}" />
ListView
will inherit its DataContext
from 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 Binding
for such controls will work perfectly.
ListView
将继承其DataContext
from Window
,因此此时它也可用。
由于ListView
就像类似的控件(例如Gridview
、ListBox
等)是 的子类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}"