我花了很多时间试图弄清楚如何将我的XML文件中的数据绑定到TreeView控件,但我不知道从哪里开始.我甚至尝试过将Xml数据双向绑定到代码项目上的WPF TreeView和Josh Smith的代码示例,但仍然无法理解如何开始!
我在文件"C:\ SPDependencies.xml"中有XML(如果需要我可以更改格式)!!!:
<node type="SPDependencies" Name="SPDependencies">
<node type="StoredProc" Name="SP1">
<node type="OperationType" Name="Type1">
<node type="TableName" Name="Table1"/>
<node type="TableName" Name="Table2"/>
</node>
<node type="OperationType" Name="Type2">
<node type="TableName" Name="Table1"/>
<node type="TableName" Name="Table2"/>
</node>
.....
</node>
<node type="StoredProc" Name="SP2">
<node type="OperationType" Name="Type1">
...
...
</node>
</node>
Run Code Online (Sandbox Code Playgroud)
我需要以下列格式在Treeview控件中显示它:
<SP1>
<Type1>
<Table1>
<Table2>
<Table3>
<Type2>
<Table1>
<Table2>
<Table3>
<SP2>
<Type1>
........
Run Code Online (Sandbox Code Playgroud)
谢谢,阿比.
给出以下xml文件:
<node type="SPDependencies" Name="SPDependencies">
<node type="StoredProc" Name="SP1">
<node type="OperationType" Name="Type1">
<node type="TableName" Name="Table1"/>
</node>
<node type="OperationType" Name="Type2">
<node type="TableName" Name="Table1"/>
</node>
</node>
<node type="StoredProc" Name="SP2">
<node type="OperationType" Name="Type1">
</node>
</node>
</node>
Run Code Online (Sandbox Code Playgroud)
视图:
<Window x:Class="Tree.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Tree"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<Window.Resources>
<HierarchicalDataTemplate x:Key="template">
<TextBlock Text="{Binding XPath=@Name}" />
<HierarchicalDataTemplate.ItemsSource>
<Binding XPath="node" />
</HierarchicalDataTemplate.ItemsSource>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid DataContext="{Binding Path=XmlData}">
<TreeView ItemsSource="{Binding}" ItemTemplate="{StaticResource template}">
</TreeView>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
查看型号:
public class ViewModel
{
public XmlDataProvider XmlData { get; set; }
public ViewModel()
{
XmlData = new XmlDataProvider();
XmlData.Source = new Uri(@"C:\input.xml");
XmlData.XPath = "node";
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
如果你只是想显示的节点下面的根,只需更改XPath来:
XmlData.XPath = "/node/node";
Run Code Online (Sandbox Code Playgroud)