我可以使用 XAML 绑定加载 XML 文件,并且没有代码。
<Window.Resources>
<XmlDataProvider x:Key="xmlfile" Source="Books.xml"/>
</Window.Resources>
<StackPanel>
<ListView ItemsSource="{Binding Source={StaticResource xmlfile}, XPath=/catalog/book, Mode=TwoWay}">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" Width="70" DisplayMemberBinding="{Binding XPath=@id}"/>
<GridViewColumn Header="Author" Width="150" DisplayMemberBinding="{Binding XPath=author}"/>
<GridViewColumn Header="Title">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding XPath=title, Mode=TwoWay}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</StackPanel>
在上面我做了title可编辑但更改标题并没有保存它,就像一个狂野的镜头。
我想知道既然代码很好地加载了 XML 文件,它是否也可以保存对文件的更改?我需要做什么来保存更改?
更新
谢谢,这可以保存但不完全保存到同一个文件。我的 books.xml 文件是项目根文件夹,带有保存按钮,它在bin\debug文件夹中保存了一个副本。如果我将工作目录设置为项目根文件夹,它不会更新文件但也不会出现错误。
我还将 XAML 中的源设置为绝对路径,因此我知道我正在使用该文件,但在这种情况下保存会引发异常。
<Window.Resources>
<XmlDataProvider x:Key="xmlfile" Source="c:\\xml\\Books.xml"/>
</Window.Resources>
例外是The given path's format is not supported.。
我也尝试了路径c:/xml/books.xml,项目以任何一种方式读取文件,但保存会引发相同的异常。
那么我真的可以将它保存到同一个文件中吗?我如何指导它做到这一点?