Linq Datagrid binding from xml file
I am developing an application in wpf in which i have one datagrid. i want the columns of datagrid to be added dynamically from xml.
<Department Name='D1' TotalCapacity='5'>
<Class Name='c1' Capacity='3'></Class>
<Class Name='c2' Capacity='2'></Class>
</Department>
<Department Name='D2' TotalCapacity='10'>
<Class Name='c1' Capacity='5'></Class>
<Class Name='c3' Capacity='5'></Class>
</Department>
Now, based on this xml i want the datagrid to be displayed as :
DepartmentName TotalCapacity c1 c2 c3
D1 开发者_如何学Python 5 3 2 -
D2 10 5 - 5
I was curious, and haven't done what you're trying to do before, so I figured I'd give it a stab. Going through this this MSDN article on the subject, I came up with this:
<Grid>
<Grid.Resources>
<XmlDataProvider x:Key="DepartmentData" XPath="Departments/Department">
<x:XData>
<Departments xmlns="">
<Department Name='D1' TotalCapacity='5'>
<Class Name='c1' Capacity='3'/>
<Class Name='c2' Capacity='2'/>
</Department>
<Department Name='D2' TotalCapacity='10'>
<Class Name='c1' Capacity='5'/>
<Class Name='c3' Capacity='5'/>
</Department>
</Departments>
</x:XData>
</XmlDataProvider>
</Grid.Resources>
<DataGrid ItemsSource="{Binding Source={StaticResource DepartmentData}}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Department Name" Binding="{Binding XPath=@Name}"/>
<DataGridTextColumn Header="Total Capacity" Binding="{Binding XPath=@TotalCapacity}"/>
<DataGridTextColumn Header="c1">
<DataGridTextColumn.Binding>
<Binding XPath="Class[@Name='c1']/@Capacity"/>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
<DataGridTextColumn Header="c2">
<DataGridTextColumn.Binding>
<Binding XPath="Class[@Name='c2']/@Capacity"/>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
<DataGridTextColumn Header="c3">
<DataGridTextColumn.Binding>
<Binding XPath="Class[@Name='c3']/@Capacity"/>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
The result:
Good luck!
Edit:
I just realized you asked for the columns to be dynamically added - I'm not sure there's a straightforward way to do that, seeing as your XML isn't structured in a format that lends itself to tabular display out of the box (I had to use some XPath magic to transform your XML to a flat format). Hopefully this will get you on the right path though.
精彩评论