I have a XML file that i’m going to use as a database for my project, this is the xml file i have:
I found this question and tryed it:
How to bind xml to the WPF DataGrid correctly?
I want to display Cadeiras of each Semestre, separately, one in each DataGrid. Changed some minors things to fit my project but it didn’t worked, after spending some hours i manage to put it working querying the XElement with this:
XElement db = XElement.Load("db.xml");
var cadeira = from elem in db.Descendants("Semestre")
where elem.Element("Nome").Value == "Semestre 1"
select elem.Element("Cadeiras");
dataGrid1.DataContext = cadeira;
First Question: This worked but i just want to know if this is the best thing to do because, this DataGrid is inside a TabItem (which is inside a TabControl), later i will have to create new TabItems (for each Semestre, with a DataGrid inside with Cadeiras of that respective Semestre) at runtime, without having the XAML binding aid.
Second Question: In XAML, what’s the difference between binding as in here How to bind xml to the WPF DataGrid correctly? and binding as this WPF Datagrid binding to xml ?
Thanks in advance.
Best regards,
-N
You can do a lot via data templating, try this example in a XAML-Parser:
This will create the TabControl and all the DataGrids for you. (In your sample the Cadeiras do not look very complex so each of them are just one row in a DataGrid, if you need one DataGrid per Cadeira you can do that as well by creating an
ItemsControlwhoseItemTemplateis aDataGrid)The difference between the methods in those questions is that they use different classes to represent the XML, normally you would not use
XElementsince that will not supportXPathin the bindings.There is no inherently correct way to do this but as there is native binding support for
XmlDataProvidersand thusXmlDocumentsi would go with that unless i have a significant reason not to.