wpf 使用 RelativeSource 绑定到父对象属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13008426/
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
Bind to Parent Object Property with RelativeSource
提问by Stef
I've built a WPF based Treeview with
我已经构建了一个基于 WPF 的 Treeview
Item
-Subitem
项目 -
子项目
If Subitem is selected, I would like to display also Properties of Item.
如果选择了子项目,我还想显示项目的属性。
<StackPanel Grid.Column="2" DataContext="{Binding ElementName=myTreeView, Path=SelectedItem}">
<TextBox Text="{Binding Path=Name, Mode=TwoWay}" />
<TextBox Text="{Binding RelativeSource={???} Path=Name, Mode=TwoWay}" />
</StackPanel>
I guess I need to use a RelativeSource statement, but not quite sure how to do so.
我想我需要使用 RelativeSource 语句,但不太确定如何使用。
回答by opewix
{Binding RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}, Path=Name, Mode=TwoWay}
回答by nmaait
JesseJames has given you the correct way to use RelativeSource but the best you will be able to do with RelativeSource is bind to the TreeViewItem itself, which is just the container for your data object i.e ViewModel, meaning you won't be able to access your data objects properties(easily).
JesseJames 为您提供了使用 RelativeSource 的正确方法,但您可以使用 RelativeSource 做的最好的事情是绑定到 TreeViewItem 本身,它只是您的数据对象(即 ViewModel)的容器,这意味着您将无法访问您的数据对象属性(很容易)。
I think in this case binding to the container object would break the View-ViewModel approach you are using. Your best bet would be to create a Parent object within your ViewModel and bind to that object. So that now each object in your collection has a reference to it's parent which can now be bound to directly.
我认为在这种情况下绑定到容器对象会破坏您正在使用的 View-ViewModel 方法。最好的办法是在 ViewModel 中创建一个 Parent 对象并绑定到该对象。所以现在你集合中的每个对象都有一个对它的父对象的引用,现在可以直接绑定到它。
<StackPanel Grid.Column="2" DataContext="{Binding ElementName=myTreeView, Path=SelectedItem}">
<TextBox Text="{Binding Path=Name, Mode=TwoWay}" />
<TextBox Text="{Binding Parent.Name}" />
</StackPanel>
Also note that the SelectedItem property returns your data object and not the container.
另请注意 SelectedItem 属性返回您的数据对象而不是容器。
回答by Tejas Sharma
I looked at your code, try binding simply to Name. It appears that your data context should already be set to the TreeViewItemdue to the following line: <StackPanel Grid.Column="2" DataContext="{Binding ElementName=myTreeView, Path=SelectedItem}">. The RelativeResourcebinding is probably looking further up the logical tree and that's why your binding is failing.
我看了你的代码,试着简单地绑定到Name. TreeViewItem由于以下行,您的数据上下文似乎已经设置为<StackPanel Grid.Column="2" DataContext="{Binding ElementName=myTreeView, Path=SelectedItem}">。该RelativeResource绑定可能进一步抬头逻辑树,这就是为什么你的绑定失败。

