Cómo: Hacer que los datos estén disponibles para el enlace en XAML

En este tema se describen varias maneras en que puede hacer que los datos estén disponibles para el enlace en lenguaje XAML, en función de las necesidades de la aplicación.

Ejemplo

Si tiene un objeto de Common Language Runtime (CLR) al que quieres enlazar desde XAML, una manera de hacer que el objeto esté disponible para el enlace es definirlo como un recurso y darle un x:Key. En el ejemplo siguiente, tiene un objeto Person con una propiedad de cadena denominada PersonName. El objeto Person (en la línea se muestra resaltado que contiene el elemento <src>) se define en el espacio de nombres denominado SDKSample.

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:src="clr-namespace:SDKSample"
  SizeToContent="WidthAndHeight"
  Title="Simple Data Binding Sample">

  <Window.Resources>
    <src:Person x:Key="myDataSource" PersonName="Joe"/>
    <Style TargetType="{x:Type Label}">
      <Setter Property="DockPanel.Dock" Value="Top"/>
      <Setter Property="FontSize" Value="12"/>
    </Style>
    <Style TargetType="{x:Type TextBox}">
      <Setter Property="Width" Value="100"/>
      <Setter Property="Height" Value="25"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
    </Style>
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Width" Value="100"/>
      <Setter Property="Height" Value="25"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
      <Setter Property="Padding" Value="3"/>
    </Style>
  </Window.Resources>
  <Border Margin="5" BorderBrush="Aqua" BorderThickness="1" Padding="8" CornerRadius="3">
    <DockPanel Width="200" Height="100" Margin="35">
      <Label>Enter a Name:</Label>
      <TextBox>
        <TextBox.Text>
          <Binding Source="{StaticResource myDataSource}" Path="PersonName"
                   UpdateSourceTrigger="PropertyChanged"/>
        </TextBox.Text>
      </TextBox>
      
      <Label>The name you entered:</Label>
      <TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=PersonName}"/>
    </DockPanel>
  </Border>
</Window>

Después, puede enlazar el control TextBlock al objeto en XAML, como se muestra en la línea resaltada que contiene el elemento <TextBlock>.

Como alternativa, puede usar la clase ObjectDataProvider, como se muestra en el ejemplo siguiente:

<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:src="clr-namespace:SDKSample"
  xmlns:system="clr-namespace:System;assembly=mscorlib"
  SizeToContent="WidthAndHeight"
  Title="Simple Data Binding Sample">

  <Window.Resources>
    <ObjectDataProvider x:Key="myDataSource" ObjectType="{x:Type src:Person}">
      <ObjectDataProvider.ConstructorParameters>
        <system:String>Joe</system:String>
      </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
    <Style TargetType="{x:Type Label}">
      <Setter Property="DockPanel.Dock" Value="Top"/>
      <Setter Property="FontSize" Value="12"/>
    </Style>
    <Style TargetType="{x:Type TextBox}">
      <Setter Property="Width" Value="100"/>
      <Setter Property="Height" Value="25"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
    </Style>
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Width" Value="100"/>
      <Setter Property="Height" Value="25"/>
      <Setter Property="DockPanel.Dock" Value="Top"/>
    </Style>
  </Window.Resources>

  <Border Margin="25" BorderBrush="Aqua" BorderThickness="3" Padding="8">
    <DockPanel Width="200" Height="100">
      <Label>Enter a Name:</Label>
      <TextBox>
        <TextBox.Text>
          <Binding Source="{StaticResource myDataSource}" Path="Name"
                   UpdateSourceTrigger="PropertyChanged"/>
        </TextBox.Text>
      </TextBox>

      <Label>The name you entered:</Label>
      <TextBlock Text="{Binding Source={StaticResource myDataSource}, Path=Name}"/>
    </DockPanel>
  </Border>
</Window>

Puede definir el enlace de la misma manera, como se muestra en la línea resaltada que contiene el elemento <TextBlock>.

En este ejemplo en concreto, el resultado es el mismo: tiene un elemento TextBlock con el contenido de texto Joe. Sin embargo, la clase ObjectDataProvider proporciona funcionalidad como la capacidad de enlazar con el resultado de un método. Puede optar por usar la clase ObjectDataProvider si necesita la funcionalidad que proporciona.

Sin embargo, si está enlazando a un objeto que ya se ha creado, debe establecer DataContext en el código, como se muestra en el ejemplo siguiente.

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;
}
Private myDataSet As DataSet

Private Sub OnInit(ByVal sender As Object, ByVal e As EventArgs)
  Dim mdbFile As String = Path.Combine(AppDataPath, "BookData.mdb")
  Dim connString As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", mdbFile)
  Dim conn As New OleDbConnection(connString)
  Dim adapter As 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
End Sub

Para acceder a datos XML para el enlace mediante la clase XmlDataProvider, consulte Enlace a datos XML mediante xmlDataProvider y consultas XPath. Para acceder a datos XML para el enlace mediante la clase ObjectDataProvider, consulte Enlace a XDocument, XElement o LINQ para resultados de consultas XML.

Para obtener información sobre muchas maneras de especificar los datos a los que está enlazando, consulte Especificación del origen de enlace. Para obtener información sobre los tipos de datos a los que puede enlazar o cómo implementar sus propios objetos de Common Language Runtime (CLR) para el enlace, consulte Información general sobre orígenes de enlace.

Vea también