下面是如何實現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 [email protected], Mode=TwoWay}" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate x:Key="rootTemplate" ItemsSource="{Binding XPath=FavoriteColors/Color}" ItemTemplate="{StaticResource colorsTemplate}">
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding [email protected], Mode=TwoWay}" />
<TextBlock Text=" " />
<TextBox Text="{Binding [email protected], Mode=TwoWay}" />
<TextBlock Text=" (Age: " />
<TextBox Text="{Binding [email protected], 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);
}
}
}
你的問題不符合問題的標題。這是關於排序一個XML文件或綁定到一個TreeView?看來你的問題只是關於XML,而不是關於WPF。一旦它被排序後,你想要綁定它,並從你說的綁定已經工作。 –
對不起,我想這需要澄清。我可以使用linq to xml輕鬆地對xml文檔進行排序,但是一旦它被排序並存儲在內存中,我該如何將它綁定到treeview? –