当父类型可以不同时,如何在 wpf 中访问父的 DataContext?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13582753/
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
How to access DataContext of parent in wpf when parent type can be different?
提问by techfun
I need to access DataContext of parent in wpf xaml. The whole xaml page code is dynamic. So don't know about the type of parent.
我需要在 wpf xaml 中访问父级的 DataContext。整个 xaml 页面代码是动态的。所以不知道父母的类型。
I am writing this
我正在写这个
<Grid DataContext={Binding Path=.}>
Is this correct?
这样对吗?
回答by khellang
Remember that if DataContextis not explicitly set, it will inherit its parent's DataContext. If, for some reason, this doesn't work, you should take a look at binding with RelativeSource.
请记住,如果DataContext未明确设置,它将继承其父级的DataContext. 如果由于某种原因,这不起作用,您应该看看 binding with RelativeSource。
Something like this might work:
像这样的事情可能会奏效:
<Grid DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext}}"
Given that the Gridhas an ancestor of type Window(which I think all controls should have).
鉴于Grid有一个祖先类型Window(我认为所有控件都应该有)。

