10. Data Provider
(1) XmlDataProvider
XmlDataProvider allows us to directly use XML data as a data source, we'll try to change the example in the previous chapter to an XML data island, and note that at this point we don't have to define the Personal, personallist type in the code.
<window x:class= "Learn.WPF.Window1"
Xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"
title= "Window1" >
<Window.Resources>
<xmldataprovider x:key= "personals" xpath= "personals" >
<x:XData>
<personals xmlns= "" >
<personal name= "Tom" age= "sex=" Male "/>"
<personal name= "Mary" age= "one" sex= "Female"/>
<personal name= "Jack" age= "sex=" Male "/>"
</Personals>
</x:XData>
</XmlDataProvider>
</Window.Resources>
<Grid>
<stackpanel datacontext= "{StaticResource personals}" >
<listbox x:name= "ListBox1" itemssource= "{Binding xpath=*}" >
<ListBox.ItemTemplate>
<DataTemplate>
<stackpanel orientation= "Horizontal" >
<textblock text= "{Binding xpath= @Name}"/>
<TextBlock>,</TextBlock>
<textblock text= "{Binding xpath= @Age}"/>
<TextBlock>,</TextBlock>
<textblock text= "{Binding xpath= @Sex}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</Window>
To define an XML data island in a resource, note that "personals xmlns" cannot be omitted, and XPath is used for binding operations (the XPath syntax can refer to the MSDN documentation). In addition to using data islands, we also use XML data files.
Window1.xaml
<window x:class= "Learn.WPF.Window1"
Xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"
Xmlns:my= "CLR-NAMESPACE:LEARN.WPF"
title= "Window1" >
<Window.Resources>
<xmldataprovider x:key= "personals" source= "Pack://siteoforigin:,,,/personals.xml"
Xpath= "Personals"/>
</Window.Resources>
<Grid>
<stackpanel datacontext= "{StaticResource personals}" >
<listbox x:name= "ListBox1" itemssource= "{Binding xpath=*}" >
<ListBox.ItemTemplate>
<DataTemplate>
<stackpanel orientation= "Horizontal" >
<textblock text= "{Binding xpath= @Name}"/>
<TextBlock>,</TextBlock>
<textblock text= "{Binding xpath= @Age}"/>
<TextBlock>,</TextBlock>
<textblock text= "{Binding xpath= @Sex}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</Window>