* Reset branch for WPF changes * Convert BMP to PNG; fix link-out-of-scope err * Add snippets for WPF... 6794 files!!!! * Add missing snippets * update file updated between migration * Fix paths to include * update breadcrumb and toc * fix index links * fix index links * fix index links * fix markdown
3.5 KiB
title, ms.date, dev_langs, helpviewer_keywords, ms.assetid
| title | ms.date | dev_langs | helpviewer_keywords | ms.assetid | ||||
|---|---|---|---|---|---|---|---|---|
| How to: Bind to XDocument, XElement, or LINQ for XML Query Results | 03/30/2017 |
|
|
6a629a49-fe1c-465d-b76a-3dcbf4307b64 |
How to: Bind to XDocument, XElement, or LINQ for XML Query Results
This example demonstrates how to bind XML data to an xref:System.Windows.Controls.ItemsControl using xref:System.Xml.Linq.XDocument.
Example
The following XAML code defines an xref:System.Windows.Controls.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 xref:System.Xml.Linq.XContainer.Element%2A and xref:System.Xml.Linq.XElement.Attribute%2A methods of the xref:System.Xml.Linq.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.
[!code-xamlXLinqExample#StackPanelResources] [!code-xamlXLinqExample#ItemsControl]
The following C# code calls xref:System.Xml.Linq.XDocument.Load%2A and sets the stack panel data context to all subelements of the element named SolarSystemPlanets in the http://planetsNS XML namespace.
[!code-csharpXLinqExample#LoadDCFromFile] [!code-vbXLinqExample#LoadDCFromFile]
XML data can be stored as a XAML resource using xref:System.Windows.Data.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.
[!code-csharpXLinqExample#LoadDCFromXAML] [!code-vbXLinqExample#LoadDCFromXAML]
The dynamic properties that map to xref:System.Xml.Linq.XContainer.Element%2A and xref:System.Xml.Linq.XElement.Attribute%2A 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.
[!code-csharpXLinqExample#BindToResults] [!code-vbXLinqExample#BindToResults]