从XML数据文件加载DataGrid

时间:2017-11-13 21:36:36

标签: c# xml wpf

我在从WPF应用程序中的XML文件加载数据时遇到问题。

XAML:

                    <DataGrid Name="dataGrid" ItemsSource="{Binding Path=Elements[Person]}" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="331" Margin="12,10,-1.774,0" VerticalAlignment="Top" Width="834" FontSize="18" FontFamily="SimSun">
                    <DataGrid.Columns>
                        <DataGridCheckBoxColumn Header="Name" Binding="{Binding Path=Element[name].Value}"  />
                        <DataGridCheckBoxColumn Header="Surname" Binding="{Binding Path=Element[surname].Value}"  />
                        <DataGridCheckBoxColumn Header="Date born" Binding="{Binding Path=Element[dateBorn].Value}" />
                    </DataGrid.Columns>
                </DataGrid>

XML文件:

<Persons> 
<Person>
<name>Test1</name> 
<surname>Test11</surname> 
<dateBorn>02.12.1990</dateBorn>
</Person>

<Person>
<name>Test2</name> 
<surname>Test22</surname> 
<dateBorn>10.12.1991</dateBorn>
</Person>

<Person>
<name>Test3</name> 
<surname>Test3</surname> 
<dateBorn>09.12.1992</dateBorn>
</Person>

我的代码:

        var peopleList = XElement.Load(dataBaseURL);
        dataGrid1.DataContext = peopleList;

我得到空单元格,并从<person> </person>标记加载数据。

2 个答案:

答案 0 :(得分:0)

您的ItemsSource看起来是正确的,绑定也是如此。

试试dataGrid1.DataContext = peopleList.Root;

答案 1 :(得分:0)

绑定应该这样纠正:

<DataGrid Name="dataGrid" ItemsSource="{Binding}" AutoGenerateColumns="False" HorizontalAlignment="Left" Height="331" Margin="12,10,-1.774,0" VerticalAlignment="Top" Width="834" FontSize="18" FontFamily="SimSun">
                <DataGrid.Columns>
                    <DataGridCheckBoxColumn Header="Name" Binding="{Binding name}"  />
                    <DataGridCheckBoxColumn Header="Surname" Binding="{Binding surname}"  />
                    <DataGridCheckBoxColumn Header="Date born" Binding="{Binding dateBorn}" />
                </DataGrid.Columns>
            </DataGrid>