How to: Bind to XDocument, XElement, or LINQ for XML Query Results
This example demonstrates how to bind XML data to an ItemsControl using XDocument.
Example
The following XAML code defines an ItemsControl and includes a data template for data of type Planet
in the http://planetsNS
XML namespace. An XML data type that occupies a namespace must include the namespace in braces, and if it appears where a XAML markup extension could appear, it must precede the namespace with a brace escape sequence. This code binds to dynamic properties that correspond to the Element and Attribute methods of the XElement class. Dynamic properties enable XAML to bind to dynamic properties that share the names of methods. To learn more, see LINQ to XML dynamic properties. Notice how the default namespace declaration for the XML does not apply to attribute names.
<StackPanel Name="stacky">
<StackPanel.Resources>
<DataTemplate DataType="{}{http://planetsNS}Planet" >
<StackPanel Orientation="Horizontal">
<TextBlock Width="100" Text="{Binding Path=Element[{http://planetsNS}DiameterKM].Value}" />
<TextBlock Width="100" Text="{Binding Path=Attribute[Name].Value}" />
<TextBlock Text="{Binding Path=Element[{http://planetsNS}Details].Value}" />
</StackPanel>
</DataTemplate>
</StackPanel.Resources>
<ItemsControl
ItemsSource="{Binding }" >
</ItemsControl>
</StackPanel>
The following C# code calls Load and sets the stack panel data context to all subelements of the element named SolarSystemPlanets
in the http://planetsNS
XML namespace.
planetsDoc = XDocument.Load("../../Planets.xml");
stacky.DataContext = planetsDoc.Element("{http://planetsNS}SolarSystemPlanets").Elements();
planetsDoc = XDocument.Load("../../Planets.xml")
stacky.DataContext = planetsDoc.Element("{http://planetsNS}SolarSystemPlanets").Elements()
XML data can be stored as a XAML resource using ObjectDataProvider. For a complete example, see L2DBForm.xaml source code. The following sample shows how code can set the data context to an object resource.
planetsDoc = (XDocument)((ObjectDataProvider)Resources["justTwoPlanets"]).Data;
stacky.DataContext = planetsDoc.Element("{http://planetsNS}SolarSystemPlanets").Elements();
planetsDoc = CType((CType(Resources("justTwoPlanets"), ObjectDataProvider)).Data, XDocument)
stacky.DataContext = planetsDoc.Element("{http://planetsNS}SolarSystemPlanets").Elements()
The dynamic properties that map to Element and Attribute provide flexibility within XAML. Your code can also bind to the results of a LINQ for XML query. This example binds to query results ordered by an element value.
stacky.DataContext =
from c in planetsDoc.Element("{http://planetsNS}SolarSystemPlanets").Elements()
orderby Int32.Parse(c.Element("{http://planetsNS}DiameterKM").Value)
select c;
stacky.DataContext = From c In planetsDoc.Element("{http://planetsNS}SolarSystemPlanets").Elements()
Order By Int32.Parse(c.Element("{http://planetsNS}DiameterKM").Value)
Select c
See also
.NET Desktop feedback