2009-04-24 48 views
2

我有一個TreeView,它建立在一個XML文件上,並在每個TreeViewItem中包含一個文本和一個圖像。 另外,我有一個TextBlock和一個Image,我想綁定到選定的TreeViewItemWPF:綁定到選定的TreeViewItem

我該怎麼做?

這是我的XAML:

<Window.Resources> 
<HierarchicalDataTemplate DataType="Node" ItemsSource ="{Binding XPath=ChildNode}"> 
    <StackPanel Orientation="Horizontal"> 
     <Image Source="{Binding [email protected]}"/> 
     <TextBlock Text="{Binding [email protected]}" /> 
    </StackPanel> 
</HierarchicalDataTemplate> 
<HierarchicalDataTemplate DataType="ChildNode" ItemsSource ="{Binding XPath=GrandchildNode}"> 
    <StackPanel Orientation="Horizontal"> 
     <Image Source="{Binding [email protected]}" /> 
     <TextBlock Text="{Binding [email protected]}" /> 
    </StackPanel> 
</HierarchicalDataTemplate> 
<DataTemplate DataType="GrandchildNode"> 
    <StackPanel Orientation="Horizontal"> 
     <Image Source="{Binding [email protected]}" /> 
     <TextBlock Text="{Binding [email protected]}" /> 
    </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> 

這裏是一個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> 

回答

6

如果你堅持你的TextBlock &圖像的另一StackPanel的內部,使之更容易一點,你可以這樣做:

<StackPanel DataContext="{Binding ElementName=treeView1, Path=SelectedItem}"> 
    <TextBlock Text="{Binding [email protected]}" /> 
    <Image Source="{Binding [email protected]}" /> 
</StackPanel>