This documentation is archived and is not being maintained.

How to: Make Data Available for Binding in XAML

This topic discusses the different 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 is defined in the namespace called SDKSample.

  Title="Simple Data Binding Sample">

    <src:Person x:Key="myDataSource" PersonName="Joe"/>



You can then bind to the object in XAML, as shown in the following example.

<TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=PersonName}"/>

Alternatively, you can use the ObjectDataProvider class, as in the following example.

<ObjectDataProvider x:Key="myDataSource" ObjectType="{x:Type src:Person}">

You define the binding the same way:

<TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=PersonName}"/>

In this particular example, the result is the same: you have a TextBlock with the text content Joe. However, the ObjectDataProvider class provides functionality such as the ability to bind to the result of a method. You can choose to use the 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.

DataSet myDataSet;

private void OnInit(object sender, EventArgs e)
  string mdbFile = Path.Combine(AppDataPath, "BookData.mdb");
  string connString = string.Format(
      "Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", mdbFile);
  OleDbConnection conn = new OleDbConnection(connString);
  OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM BookTable;", conn);

  myDataSet = new DataSet();
  adapter.Fill(myDataSet, "BookTable");

  // myListBox is a ListBox control.
  // Set the DataContext of the ListBox to myDataSet
  myListBox.DataContext = myDataSet;

To access XML data for binding using the XmlDataProvider class, see How to: Bind to XML Data Using an XMLDataProvider and XPath Queries. To access XML data for binding using the ObjectDataProvider class, see How to: Bind to XDocument, XElement, or LINQ for XML Query Results.

For information about the different ways you can specify the data you are binding to, see How to: 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.