简体   繁体   中英

Loading DataGrid from XML data file

I have a problem with loading data from an XML file in a WPF application.

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

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

My code:

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

I get empty cells and I load data from <person> </person> tags.

Your ItemsSource looks correct, so do the bindings.

Try dataGrid1.DataContext = peopleList.Root; ?

The bindings should be corrected as such:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM