In WPF, we can easily bind WPF controls with xml data using XmlDataProvider. Using XmlDataProvider, we can bind xml data in XAML file itself without writing any code in code behind.
Here, below is the example of XmlDataProvider.
For binding xml data using XmlDataProvider ,first we require xml file that contains data.
XML file:
<?xml version="1.0"?>
<Groups>
<Group>
<Id>1</Id>
<Name>Group 1</Name>
<Images>
<ImageName>Image1</ImageName>
<ImageName>Image2</ImageName>
<ImageName>Image3</ImageName>
</Images>
</Group>
<Group>
<Id>2</Id>
<Name>Group 2</Name>
<Images>
<ImageName>Image4</ImageName>
<ImageName>Image5</ImageName>
<ImageName>Image6</ImageName>
<ImageName>Image7</ImageName>
</Images>
</Group>
<Group>
<Id>3</Id>
<Name>Group 3</Name>
<Images>
<ImageName>Image8</ImageName>
<ImageName>Image9</ImageName>
</Images>
</Group>
<Group>
<Id>4</Id>
<Name>Group 4</Name>
<Images>
<ImageName>Image10</ImageName>
<ImageName>Image11</ImageName>
<ImageName>Image12</ImageName>
<ImageName>Image13</ImageName>
<ImageName>Image14</ImageName>
<ImageName>Image15</ImageName>
<ImageName>Image16</ImageName>
</Images>
</Group>
</Groups>
In XAML:
In XmlDataProvider,
1. In Source -we have to pass path of xml file.
2. In XPath- we have to pass path required xml node
<XmlDataProvider x:Key="groupConfigurationXmlDataProvider" Source="XmlFiles/ImagesConfiguration.xml" XPath="/Groups" />
Here below, I bind ItemsControl using XmlDataProvider.
In DataContext- Provide XmlDataProvider. In my case it is "groupConfigurationXmlDataProvider".
In ItemSource- Provide xml node path.
In Content- Provide the node which you have to display.In my case I provide "Name" .
Binding Item Control:
<ItemsControl HorizontalAlignment="Left" VerticalAlignment="Bottom" DataContext="{Binding Source={StaticResource groupConfigurationXmlDataProvider}}" ItemsSource="{Binding XPath=Group}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding XPath=Name}" Tag="{Binding}" Style="{StaticResource Button_Header}" Click="Button_Click" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Hope, this code will help you. Thanks
0 Comment(s)