直接在xaml定义时xml时应该注意的!
xml数据
<?xml version="1.0" encoding="utf-8"?> <StringList > <Srtring Id="1"> <Name>A</Name> <Age>10</Age> <Nub>001</Nub> </Srtring> <Srtring Id="2"> <Name>B</Name> <Age>20</Age> <Nub>002</Nub> </Srtring> <Srtring Id="3"> <Name>C</Name> <Age>30</Age> <Nub>003</Nub> </Srtring> <Srtring Id="4"> <Name>D</Name> <Age>40</Age> <Nub>004</Nub> </Srtring> <Srtring Id="5"> <Name>A</Name> <Age>50</Age> <Nub>005</Nub> </Srtring> </StringList>
如果直接在Xaml页面中定义则是:
使用XmlDataProvider,并设置key,以及Xpath的源,xpath则是xml在被绑定时起始数据的起点,但不包括自身(不设置也可以,但是需要在设置绑定时设置)
也就是xpath设定为StringList,绑定时的起点则是String
且注意的是:XAML页面中不可以包含<?xml version="1.0" ?>字样,会报错。还有需要在xml根部加上xmlns=""
例子:
<Window.Resources> <XmlDataProvider x:Key="xmlData" > <x:XData> <StringList xmlns=""> <String Id="1"> <Name>A</Name> <Age>10</Age> <Nub>001</Nub> </String> <String Id="2"> <Name>B</Name> <Age>20</Age> <Nub>002</Nub> </String> <String Id="3"> <Name>C</Name> <Age>30</Age> <Nub>003</Nub> </String> <String Id="4"> <Name>D</Name> <Age>40</Age> <Nub>004</Nub> </String> <String Id="5"> <Name>A</Name> <Age>50</Age> <Nub>005</Nub> </String> </StringList> </x:XData> </XmlDataProvider> </Window.Resources> <Grid> <ListView ItemsSource="{Binding Source={StaticResource xmlData},XPath=StringList/*}"> <ListView.View> <GridView> <GridViewColumn Header="Name" Width="60" DisplayMemberBinding="{Binding XPath=Name}" /> <GridViewColumn Header="Age" Width="60" DisplayMemberBinding="{Binding XPath=Age}" /> <GridViewColumn Header="Nub" Width="60" DisplayMemberBinding="{Binding XPath=Nub}" /> </GridView> </ListView.View> </ListView> </Grid>
如果想要获取属性则是需要使用@,并且确保xpath路径正确
例如
<ListView ItemsSource="{Binding Source={StaticResource xmlData},XPath=/StringList/*}"> <ListView.View> <GridView> <GridViewColumn Header="Id" Width="60" DisplayMemberBinding="{Binding XPath=@Id}" /> <GridViewColumn Header="Id" Width="60" DisplayMemberBinding="{Binding XPath=Age}" /> <GridViewColumn Header="Id" Width="60" DisplayMemberBinding="{Binding XPath=Nub}" /> </GridView> </ListView.View> </ListView>
截图