Click here to Skip to main content
15,795,331 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to bind my grid to data from an Xml file. I've used xsd.exe to create a first a schema from the xml, and then a class file from the schema. I can bind the data to the grid in code, but can't find how to do so in the designer. In winforms I would create a DataSource from the object, and could use that to configure the DataGridView columns in the designer; but I can't find a way to point DataGrid.ItemSource to it in the WPF designer.

My xaml,

<DataGrid AutoGenerateColumns="True" HorizontalAlignment="Stretch" Margin="12,320,12,12" Name="dataGrid1" VerticalAlignment="Stretch"  />

XmlReader reader = XmlReader.Create(filePath);
XmlSerializer serializer = new XmlSerializer(typeof(myXml));
myXml data = new myXml();
data = (myXml)serializer.Deserialize(myXml);

//data.entry is an array of myXmlEntry objects
dataGrid1.ItemsSource = data.entry;

1 solution

You need to reference the XML in the resources, you can do this typically by :
  <XmlDataProvider x:Key="MyXML" d:IsDataSource="True" Source="MyXml.xml" />
Then, hook up in your datagrid using
ItemsSource="{Binding Source={StaticResource MyXML}}"
Share this answer
Dan Neely 7-Nov-10 14:55pm    
Is the 1st code snippet supposed to go into the .xaml file? If so, where do I need to place it so that it compiles?
Pete O'Hanlon 7-Nov-10 14:57pm    
Dan - take a look at my article at to see an example, including where to put this.
Dan Neely 7-Nov-10 15:13pm    
When I put the xml there, the compiler pukes on me; it appears that d:IsDataSource="True" is only supported by Expression Blend which I don't have, and which is completely outside my budget for a personal project. I tried removing the offending attribute, at which point the compiler was happy and I could specify the binding source; but the generate/remove/edit property bound columns items in the visual studio properties panel all still error out with "you must set ItemSource before you can perform this action."
Dan Neely 7-Nov-10 15:14pm    
A second question, is that setup locking me into a single file as the datasource? I hard coded one in for my initial testing but will need to be able to support switching between several once I'm finished.
Pete O'Hanlon 7-Nov-10 15:20pm    
Dan - you've now reached the point where you need to look into MVVM. Basically, you'd read your data in and hook up through your ViewModel.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900