title | description | ms.date | dev_langs | helpviewer_keywords | ms.assetid | ||||
---|---|---|---|---|---|---|---|---|---|
How to: Make Data Available for Binding in XAML |
Discover the various ways you can make data available according to the needs of your application in Windows Presentation Foundation (WPF). |
01/29/2018 |
|
|
7103c2e8-0e31-4a13-bf12-ca382221a8d5 |
This topic discusses various ways you can make data available for binding in Extensible Application Markup Language (XAML), depending on the needs of your application.
If you have a common language runtime (CLR) object you would like to bind to from XAML, one way you can make the object available for binding is to define it as a resource and give it an x:Key
. In the following example, you have a Person
object with a string property named PersonName
. The Person
object (in the line shown highlighted that contains the <src>
element) is defined in the namespace called SDKSample
.
[!code-xamlSimpleBinding#Instantiation]
You can then bind the xref:System.Windows.Controls.TextBlock control to the object in XAML, as the highlighted line that contains the <TextBlock>
element shows.
Alternatively, you can use the xref:System.Windows.Data.ObjectDataProvider class, as in the following example:
[!code-xamlObjectDataProvider}]
You define the binding the same way, as the highlighted line that contains the <TextBlock>
element shows.
In this particular example, the result is the same: you have a xref:System.Windows.Controls.TextBlock with the text content Joe
. However, the xref:System.Windows.Data.ObjectDataProvider class provides functionality such as the ability to bind to the result of a method. You can choose to use the xref:System.Windows.Data.ObjectDataProvider class if you need the functionality it provides.
However, if you are binding to an object that has already been created, you need to set the DataContext
in code, as in the following example.
[!code-csharpADODataSet#1] [!code-vbADODataSet#1]
To access XML data for binding using the xref:System.Windows.Data.XmlDataProvider class, see Bind to XML Data Using an XMLDataProvider and XPath Queries. To access XML data for binding using the xref:System.Windows.Data.ObjectDataProvider class, see Bind to XDocument, XElement, or LINQ for XML Query Results.
For information about many ways you can specify the data you are binding to, see Specify the Binding Source. For information about what types of data you can bind to or how to implement your own common language runtime (CLR) objects for binding, see Binding Sources Overview.