Ste*_*tef 2 c# wpf treeview binding relativesource
我已经构建了一个基于WPF的Treeview
项目 -
子项目
如果选择了Subitem,我还想显示Item of Properties.
<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>
Run Code Online (Sandbox Code Playgroud)
我想我需要使用RelativeSource语句,但不太确定如何这样做.
{Binding RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}, Path=Name, Mode=TwoWay}
Run Code Online (Sandbox Code Playgroud)
JesseJames已经为您提供了使用RelativeSource的正确方法,但是您可以使用RelativeSource最好的方法是绑定到TreeViewItem本身,它只是您的数据对象的容器,即ViewModel,这意味着您将无法访问数据对象属性(很容易).
我认为在这种情况下,绑定到容器对象会破坏您正在使用的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>
Run Code Online (Sandbox Code Playgroud)
另请注意,SelectedItem属性返回数据对象而不是容器.