从xml文件绑定Linq Datagrid

时间:2011-07-26 04:01:31

标签: wpf xml linq datagrid

我正在开发一个wpf中的应用程序,其中我有一个数据网格。我希望从xml动态添加datagrid列。

<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>

现在,基于这个xml我希望datagrid显示为:

DepartmentName TotalCapacity c1 c2 c3

 D1                  5      3 2  -  

 D2                 10      5 -  5

1 个答案:

答案 0 :(得分:0)

我很好奇,并没有做过你之前想做的事情,所以我想我会给它一个刺。通过关于这个主题的this MSDN article,我想出了这个:

<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

祝你好运!

修改

我刚刚意识到你要求动态添加列 - 我不确定是否有一种直接的方法可以做到这一点,因为你的XML的结构格式不适合开箱即用的表格式显示(我不得不使用一些XPath魔法将XML转换为平面格式)。希望这会让你走上正确的道路。