Binding WPF C1DataGrid to XML File

Windows Presentation Foundation (WPF) provides developers with a vast amount of data binding functionality. However, one area where the data binding falls short is with the XmlDataProvider. XmlDataProvider Class enables declarative access to XML data for data binding. With an XmlDataProvider, the underlying data that can be accessed through data binding in your application can be any tree of XML nodes. In other words, an XmlDataProvider provides a convenient way to use any tree of XML nodes as a binding source. This article demonstrates how to bind C1DataGrid to XML data using an XmlDataProvider. Let's create an XML with some test data and name it "Customer.xml":

<?xml version="1.0" encoding="utf-8"?>  
 <Customer Name="Tom Clancy" Address="Address1" City="NewYork" Phone="443322" />  
 <Customer Name="Frederick Forsyth" Address="Address2" City="NewJersey" Phone="558652" />  
 <Customer Name="Robert Ludlum" Address="Address3" City="NewHampshire" Phone="654821" />  
 <Customer Name="Dan Brown" Address="Address4" City="Seattle" Phone="225566" />  
 <Customer Name="Arthur C Clarke" Address="Address5" City="Atlanta" Phone="998855" />  
 <Customer Name="Robin Cook" Address="Address6" City="California" Phone="774411" />  
 <Customer Name="David Baldacci" Address="Address6" City="Texas" Phone="774411" />  

Now, XmlDataProvider specifies the underlying source XML file through its Source attribute. The XPath attribute is used to specify the level at which the data binding occurs. The x:Key attribute exposes the XmlDataProvider to the code-behind.

 <XmlDataProvider Source="Customer.xml" XPath="Customers" x:Key="custData" />  

Note: The binding does not have to be done at the Grid level. We could bind C1DataGrid and other controls to the data within the XmlDataProvider individually. However, there is a synchronization issue when multiple controls bind directly to the XmlDataProvider and use the XPath statement. The next item in the binding architecture is the C1Datagrid. Since C1Datagrid is contained within the Grid, and the Grid is bound to the data at the ''Customer" level, the bindings can be inherited. We can accomplish this simply by setting the C1Datagrid's ItemsSource property to the current bindings.

<my:C1DataGrid Name="c1DataGrid1" AutoGenerateColumns="False" ItemsSource="{Binding Source={StaticResource  
  <my:DataGridTextColumn Binding="{Binding XPath=@Name}" Header="Name" />  
  <my:DataGridTextColumn Binding="{Binding XPath=@Address}" Header="Address" />  
  <my:DataGridTextColumn Binding="{Binding XPath=@City}" Header="City" />  
  <my:DataGridTextColumn Binding="{Binding XPath=@Phone}" Header="Phone" />  

And, this is how C1Datagrid bound to an XML datasource looks like screenshot Download C# Sample Download Sample


GrapeCity Developer Tools
comments powered by Disqus