wpf 如何在 Windows 8 商店应用程序中访问父级的 DataContext
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15366609/
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 Parent's DataContext in Windows 8 store apps
提问by Tilak
This is a common situation in XAML based apps (WPF/Silverlight/WinRT).
这是基于 XAML 的应用程序(WPF/Silverlight/WinRT)中的常见情况。
WPF related link -> WPF Databinding: How do I access the "parent" data context?
WPF 相关链接 -> WPF 数据绑定:如何访问“父”数据上下文?
RelativeSourcewith AncestorType, and Mode=FindAncestorusually comes to rescue in WPF.
RelativeSource与AncestorType,Mode=FindAncestor通常会在 WPF 中进行救援。
Both of these are missing in WinRT API. How to access the Parent's (may not be immediate one), DataContext?
WinRT API 中缺少这两者。如何访问父母的(可能不是直接的)DataContext,?
(I am aware of TemplateBinding, and ElementBindingbut both are not suitable mostly in DataTemplate).
(我知道TemplateBinding,ElementBinding但两者都不太适合在 DataTemplate 中使用)。
回答by LMK
I just had the same problem. Presumably this is common??
我只是遇到了同样的问题。想必这很常见吧??
Here is a crude solution that works:
这是一个有效的粗略解决方案:
Bind the Tag property of a top level element to the DataContext
<Grid Name="gridTop" Tag="{Binding}" />Bind the property you want via ElementName in nested element, ie
{Binding Tag.SomeProp, ElementName=gridTop}
将顶级元素的 Tag 属性绑定到 DataContext
<Grid Name="gridTop" Tag="{Binding}" />通过嵌套元素中的 ElementName 绑定你想要的属性,即
{Binding Tag.SomeProp, ElementName=gridTop}
回答by Filip Skakun
ElementName binding is still possible and might work in your case. Otherwise you'd need to implement an attached behavior.
ElementName 绑定仍然是可能的,并且可能适用于您的情况。否则你需要实现一个附加的行为。
回答by Denis
There are several ways you can deal with this issue:
有几种方法可以处理这个问题:
ElementName binding is the most common approach, as Filip pointed out.
正如 Filip 指出的那样,ElementName 绑定是最常见的方法。
You could walk visual tree till you find the parent. That is what FindAcestor does internally. You could dress it up in behavior for easy reuse.
你可以走视觉树直到你找到父母。这就是 FindAcestor 在内部所做的。你可以把它打扮成行为,以便于重用。
If you use view models you could use messages instead of bindings or you could add parent context to each child view model.
如果您使用视图模型,您可以使用消息而不是绑定,或者您可以向每个子视图模型添加父上下文。
Picking the best solution will depend on your specific circumstances.
选择最佳解决方案将取决于您的具体情况。

