我很难掌握WPF,更具体地说是执行xml文件的双向绑定。我应该使用XMLDataProvider还是他们的另一个(更好)选项? 数据显示正常,但是当我更改条目时,更改不会反映在xml文件中。
XML:
<?xml version="1.0" encoding="utf-8" ?>
<Licence>
<Market>
<Name>DAX</Name>
<Begin>01/01/2010</Begin>
<End>01/04/2010</End>
</Market>
<Market>
<Name>DJI</Name>
<Begin>01/07/2010</Begin>
<End>01/10/2010</End>
</Market>
</Licence>
XAML:
<Window x:Class="WpfApplication5.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>
<DataTemplate x:Key="LicenceTemplate">
<Label Content="{Binding XPath=Name}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.DataContext>
<XmlDataProvider x:Name="XMLData" Source="XMLFile1.xml" XPath="Licence/Market"/>
</Grid.DataContext>
<StackPanel>
<DataGrid x:Name="DataGridLic" ItemsSource="{Binding}" AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="300" CellEditEnding="DataGridLic_CellEditEnding">
<DataGrid.Columns>
<DataGridTextColumn x:Name="nameColumn" Binding="{Binding XPath=Name, Mode=TwoWay}" Header="Name" Width="100" Foreground="#FFC28383" />
<DataGridTextColumn x:Name="BegColumn" Binding="{Binding XPath=Begin, Mode=TwoWay}" Header="Begin" Width="100" Foreground="#FFC14040" />
<DataGridTextColumn x:Name="EndColumn" Binding="{Binding XPath=End, Mode=TwoWay}" Header="End" Width="100" Foreground="#FFC14040" />
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
CodeBehind:
public MainWindow()
{
InitializeComponent();
}
private void DataGridLic_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
XMLData.Document.Save("XMLFile1.xml");
}
更新: xml数据绑定的一些有用资源:
答案 0 :(得分:2)
使用XMLDataProvider没问题。您只需要确保您正在读取和写入相同的XML文件。
只需更新您的代码,如下所示;
public MainWindow()
{
InitializeComponent();
var xmlFilePath = @"c:\whatever\XMLFile1.xml";
XMLData.Source = new Uri(xmlFilePath);
}
private void DataGridLic_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
var xmlSource = XMLData.Source.LocalPath;
XMLData.Document.Save(xmlSource);
}