下面是一个如何实现 XML 到 TreeView 绑定的基本示例。XmlDataProvider 允许您加载 XML 文档并绑定到它。HierarchicalDataTemplate 允许您定义带有子项的 TreeView 模板。必须使用 XPath 而不是 Path 来绑定,@ 符号前缀表示绑定到属性。
<Window x:Class="Testing.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<XmlDataProvider x:Key="people" XPath="People" />
<HierarchicalDataTemplate x:Key="colorsTemplate">
<TextBox Text="{Binding XPath=@Name, Mode=TwoWay}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="rootTemplate" ItemsSource="{Binding XPath=FavoriteColors/Color}" ItemTemplate="{StaticResource colorsTemplate}">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding XPath=@FirstName, Mode=TwoWay}" />
<TextBlock Text=" " />
<TextBox Text="{Binding XPath=@LastName, Mode=TwoWay}" />
<TextBlock Text=" (Age: " />
<TextBox Text="{Binding XPath=@Age, Mode=TwoWay}" />
<TextBlock Text=")" />
</StackPanel>
</HierarchicalDataTemplate>
</Window.Resources>
<Grid>
<TreeView ItemsSource="{Binding Source={StaticResource people}, XPath=Person}" ItemTemplate="{StaticResource rootTemplate}" Grid.ColumnSpan="2" />
</Grid>
</Window>
使用以下 XML 文件:
<?xml version="1.0" encoding="utf-8" ?>
<People>
<Person FirstName="Ringo" LastName="Starr" Age="72">
<FavoriteColors />
</Person>
<Person FirstName="George" LastName="Harrison" Age="52">
<FavoriteColors>
<Color Name="Orange" />
<Color Name="Green" />
<Color Name="Purple" />
</FavoriteColors>
</Person>
<Person FirstName="Paul" LastName="McCartney" Age="42">
<FavoriteColors>
<Color Name="White" />
</FavoriteColors>
</Person>
<Person FirstName="John" LastName="Lennon" Age="33">
<FavoriteColors>
<Color Name="Red" />
<Color Name="Green" />
</FavoriteColors>
</Person>
</People>
以及以下代码隐藏:
XmlDataProvider people;
public MainWindow()
{
InitializeComponent();
people = FindResource("people") as XmlDataProvider;
var xmlDocument = new XmlDocument();
xmlDocument.Load("People.xml");
people.Document = xmlDocument;
}
如您所见,我正在代码中加载 XML 文档,因此您可以将其加载到 XDocument 或 XmlDocument 类中并按照您的需要对其进行排序。然后你应该能够在某个时候将它保存回文件。
编辑:
这是在运行时加载和保存的示例:
private void Load_Click(object sender, RoutedEventArgs e)
{
var xmlDocument = new XmlDocument();
xmlDocument.Load("People.xml");
people.Document = xmlDocument;
}
private void Save_Click(object sender, RoutedEventArgs e)
{
XmlDocument xml = people.Document;
if (xml != null)
{
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
if ((bool)sfd.ShowDialog(this))
{
xml.Save(sfd.FileName);
}
}
}