我在google上搜索了一些类似的问题,但是还没有找到答案。我将xml文件绑定到WPF中的treeview控件。使用这文章,我可以很容易地用我的xml文件建立双向的数据库。
但是,在附加xml文档之前,我想将排序应用于xml文档。我正在建模一个任务管理器,其中任务包含开始日期和到期日期,我想通过等待到期日来订购节点,所以最紧急的任务首先出现。我对Linq到XML有一些经验,但不知道如何处理绑定问题。有什么想法吗?
因此,在阅读了更多之后,这里是我的伪代码:
有人能帮我把这个冲掉吗?
发布于 2012-06-08 18:59:51
下面是如何实现的一个基本示例。XmlDataProvider允许您加载一个XML文档并绑定到它。HierarchicalDataTemplate允许您定义带有子项的TreeView模板。XPath必须用于绑定而不是路径,@符号前缀指示绑定到属性。
<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);
}
}
}
https://stackoverflow.com/questions/10953835
复制相似问题