我试图将XML数据绑定到DataView。我跟随this guide但是即使我可以在Visual Studio 2013下看到结果,我在运行程序时也看不到结果。我尝试将Movies.xml添加到Resources并将其添加到项目目录中。目前它位于项目根路径下。当我写这篇文章时,有一段时间我在项目运行时看到了结果,但是在干净的构建之后它又消失了。
Movies.XML:
<?xml version="1.0" encoding="utf-8" ?>
<Movies xmlns="">
<Movie Name="Seven Samurai" Id="101" Director="Akira Kurosawa" />
<Movie Name="Happy Together" Id="102" Director="Wong Kar Wai"/>
<Movie Name="Shoot The Piano Player" Id="103" Director="Francois Truffaut"/>
<Movie Name="Roshomon" Id="104" Director="Akira Kurosawa" />
<Movie Name="Dead Man" Id="105" Director="Jim Jarmusch"/>
<Movie Name="Children of Heaven" Id="106" Director="Majid Majidi"/>
</Movies>
XAML:
<Window x:Class="DataGridXML.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">
<Grid>
<Grid.Resources>
<XmlDataProvider x:Key="MovieData" Source="Movies.xml" XPath="/Movies/Movie"/>
</Grid.Resources>
<DataGrid x:Name="dgridEmp" DataContext="{StaticResource MovieData}" ItemsSource="{Binding XPath=/Movies/Movie}"
AutoGenerateColumns="False" Margin="52,89,31,50">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding XPath=@Name}" />
<DataGridTextColumn Header="Title" Binding="{Binding XPath=@Director}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Visual Studio预览:
项目运行时间:
我的最终目标是动态绑定此类XML,以便用户选择要解析的XML。然后用户可以更改内容并保存。
答案 0 :(得分:3)
您可以这样做,首先将您的xml转换为DataSet
,然后只需将DataGrid
的{{1}}设置为ItemsSource
:
DataView
XAML:
string sampleXmlFile = @"C:\Users\umut.koseali\Desktop\test.xml";
DataSet dataSet = new DataSet();
dataSet.ReadXml(sampleXmlFile);
DataView dataView = new DataView(dataSet.Tables[0]);
dataGrid1.ItemsSource = dataView
答案 1 :(得分:1)