use*_*493 2 wpf treeview binding hierarchicaldatatemplate
我有一个TreeView建立在XML文件上的文件,每个文件都包含一个文本和一个图像 TreeViewItem.此外,我有一个TextBlock和一个Image,我想绑定到选定的TreeViewItem.
我怎样才能做到这一点?
这是我的XAML:
<Window.Resources>
<HierarchicalDataTemplate DataType="Node" ItemsSource ="{Binding XPath=ChildNode}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding XPath=@Image}"/>
<TextBlock Text="{Binding XPath=@Name}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="ChildNode" ItemsSource ="{Binding XPath=GrandchildNode}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding XPath=@Image}" />
<TextBlock Text="{Binding XPath=@Name}" />
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="GrandchildNode">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding XPath=@Image}" />
<TextBlock Text="{Binding XPath=@Name}" />
</StackPanel>
</DataTemplate>
<XmlDataProvider x:Key="xmlNodeList" Source="XMLFile1.xml" XPath="Root"/></Window.Resources><StackPanel>
<TreeView Name="treeView1" ItemsSource="{Binding Source={StaticResource xmlNodeList}, XPath=Node}" />
<TextBlock />
<Image /></StackPanel>
Run Code Online (Sandbox Code Playgroud)
这是一个XML数据:
<Root>
<Node Name="AAA" Image="images/1.ico" />
<Node Name="BBB" Image="images/2.ico">
<ChildNode Name="bbb 1" Image="images/3.ico">
<GrandchildNode Name="b 1.1" Image="images/4.ico"/>
<GrandchildNode Name="b 1.2" Image="images/5.ico"/>
<GrandchildNode Name="b 1.3" Image="images/6.ico"/>
</ChildNode>
<ChildNode Name="bbb 2" Image="images/7.ico"/>
<ChildNode Name="bbb 3" Image="images/8.ico">
<GrandchildNode Name="b 3.1" Image="images/9.ico"/>
<GrandchildNode Name="b 3.2" Image="images/10.ico"/>
</ChildNode>
<ChildNode Name="bbb 4" Image="images/11.ico"/>
</Node>
<Node Name="CCC" Image="images/12.ico">
<ChildNode Name="ccc 1" Image="images/13.ico">
<GrandchildNode Name="c 1.1" Image="images/14.ico"/>
<GrandchildNode Name="c 2.2" Image="images/15.ico"/>
</ChildNode>
</Node></Root>
Run Code Online (Sandbox Code Playgroud)
如果您将TextBlock&Image粘贴到另一个StackPanel中以使其更容易,您可以执行以下操作:
<StackPanel DataContext="{Binding ElementName=treeView1, Path=SelectedItem}">
<TextBlock Text="{Binding XPath=@Name}" />
<Image Source="{Binding XPath=@Image}" />
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7321 次 |
| 最近记录: |