我已按照本文的建议将树视图控件绑定到 xml 文档: http ://www.codeproject.com/Articles/317766/Displaying-XML-in-a-WPF-TreeView?msg=4546407#xx4546407xx
但是,现在我不知道如何访问所选项目。
这是我的 XAML:
<Window.Resources>
<XmlDataProvider x:Key="xmldata" Source="cats.xml" XPath="/CategoryArray" />
<HierarchicalDataTemplate DataType="Category" ItemsSource="{Binding XPath=./*}">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5,0,0,0" Text="{Binding XPath=@Name}" Tag="{Binding XPath=@ID}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="CategoryArray" ItemsSource="{Binding XPath=./*}">
<TextBlock Margin="0" Text="eBay Categories" />
</HierarchicalDataTemplate>
</Window.Resources>
<Grid DataContext="{StaticResource xmldata}">
<TreeView Name="treeView1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding}" VirtualizingStackPanel.IsVirtualizing="False" VirtualizingStackPanel.VirtualizationMode="Standard" SelectedItemChanged="treeView1_SelectedItemChanged" />
</Grid>
这似乎不像我想象的那样工作:
private void treeView1_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
try
{
TreeViewItem selectedItem = treeView1.SelectedValue as TreeViewItem;
categoryName = selectedItem.Name;
categoryID = selectedItem.Tag.ToString();
categoryChosen = true;
}
catch { }
}
由于我使用的是这个分层数据模板和一个文本块,我不知道该怎么做。有任何想法吗?提前致谢。