Cómo: Especificar el origen de enlace

En el enlace de datos, el objeto de origen de enlace hace referencia al objeto del que se obtienen los datos. En este tema se describen las distintas maneras de especificar el origen de enlace.

Ejemplo

Para enlazar varias propiedades a un mismo origen, utilice la propiedad DataContext, que proporciona una manera cómoda de establecer un ámbito dentro del cual todas las propiedades enlazadas a datos heredan un origen común.

En el ejemplo siguiente, el contexto de datos se establece en el elemento raíz de la aplicación. Esto permite que todos los elementos secundarios hereden ese contexto de datos. Los datos para el enlace proceden de una clase de datos personalizada, NetIncome, a la que se hace referencia directamente mediante una asignación que recibe la clave de recurso de incomeDataSource.

<Grid
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="SDKSample.DirectionalBinding"
  xmlns:c="clr-namespace:SDKSample"
  Name="Page1"
>
  <Grid.Resources>
    <c:NetIncome x:Key="incomeDataSource"/>
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Padding" Value="8"/>
    </Style>
    <Style TargetType="{x:Type TextBox}">
      <Setter Property="Margin" Value="0,6,0,0"/>
    </Style>
  </Grid.Resources>
  <Grid.DataContext>
    <Binding Source="{StaticResource incomeDataSource}"/>
  </Grid.DataContext>


...


</Grid>

En el ejemplo siguiente, se muestra la definición de la clase NetIncome.

Public Class NetIncome
    Implements INotifyPropertyChanged

    ' Events
    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    ' Methods
    Public Sub New()
        Me._totalIncome = 5000
        Me._rent = 2000
        Me._food = 0
        Me._misc = 0
        Me._savings = 0
        Me._savings = (Me.TotalIncome - ((Me.Rent + Me.Food) + Me.Misc))
    End Sub

    Private Sub OnPropertyChanged(ByVal info As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
    End Sub

    Private Sub UpdateSavings()
        Me.Savings = (Me.TotalIncome - ((Me.Rent + Me.Misc) + Me.Food))
        If ((Me.Savings >= 0) AndAlso (Me.Savings >= 0)) Then
        End If
    End Sub


    ' Properties
    Public Property Food As Integer
        Get
            Return Me._food
        End Get
        Set(ByVal value As Integer)
            If (Me.Food <> value) Then
                Me._food = value
                Me.OnPropertyChanged("Food")
                Me.UpdateSavings()
            End If
        End Set
    End Property

    Public Property Misc As Integer
        Get
            Return Me._misc
        End Get
        Set(ByVal value As Integer)
            If (Me.Misc <> value) Then
                Me._misc = value
                Me.OnPropertyChanged("Misc")
                Me.UpdateSavings()
            End If
        End Set
    End Property

    Public Property Rent As Integer
        Get
            Return Me._rent
        End Get
        Set(ByVal value As Integer)
            If (Me.Rent <> value) Then
                Me._rent = value
                Me.OnPropertyChanged("Rent")
                Me.UpdateSavings()
            End If
        End Set
    End Property

    Public Property Savings As Integer
        Get
            Return Me._savings
        End Get
        Set(ByVal value As Integer)
            If (Me.Savings <> value) Then
                Me._savings = value
                Me.OnPropertyChanged("Savings")
                Me.UpdateSavings()
            End If
        End Set
    End Property

    Public Property TotalIncome As Integer
        Get
            Return Me._totalIncome
        End Get
        Set(ByVal value As Integer)
            If (Me.TotalIncome <> value) Then
                Me._totalIncome = value
                Me.OnPropertyChanged("TotalIncome")
            End If
        End Set
    End Property


    ' Fields
    Private _food As Integer
    Private _misc As Integer
    Private _rent As Integer
    Private _savings As Integer
    Private _totalIncome As Integer
End Class
public class NetIncome : INotifyPropertyChanged
{
    private int totalIncome = 5000;
    private int rent = 2000;
    private int food = 0;
    private int misc = 0;
    private int savings = 0;
    public NetIncome()
    {
        savings = totalIncome - (rent+food+misc);
    }

    public int TotalIncome
    {
        get
        {
            return totalIncome;
        }
        set
        {
            if( TotalIncome != value)
            {
                totalIncome = value;
                OnPropertyChanged("TotalIncome");
            }
        }
    }
    public int Rent
    {
        get
        {
            return rent;
        }
        set
        {
            if( Rent != value)
            {
                rent = value;
                OnPropertyChanged("Rent");
                UpdateSavings();
            }
        }
    }
    public int Food
    {
        get
        {
            return food;
        }
        set
        {
            if( Food != value)
            {
                food = value;
                OnPropertyChanged("Food");
                UpdateSavings();
            }
        }
    }
    public int Misc
    {
        get
        {
            return misc;
        }
        set
        {
            if( Misc != value)
            {
                misc = value;
                OnPropertyChanged("Misc");
                UpdateSavings();
            }
        }
    }
    public int Savings
    {
        get
        {
            return savings;
        }
        set
        {
            if( Savings != value)
            {
                savings = value;
                OnPropertyChanged("Savings");
                UpdateSavings();
            }
        }
    }

    private void UpdateSavings()
    {
        Savings = TotalIncome - (Rent+Misc+Food);
        if(Savings < 0)
        {}
        else if(Savings >= 0)
        {}
    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(String info)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler !=null)
        {
            handler(this, new PropertyChangedEventArgs(info));
        }
    }
}
NotaNota

En el ejemplo anterior se crea una instancia del objeto en marcado y se utiliza como recurso.Si desea enlazar a un objeto del que ya se ha creado una instancia en el código, deberá establecer la propiedad DataContext mediante programación.Para obtener un ejemplo, vea Cómo: Hacer que los datos estén disponibles para el enlace en XAML.

Como alternativa, si desea especificar explícitamente el origen en los enlaces individuales, dispone de las opciones siguientes. Éstas tienen prioridad sobre el contexto de datos heredado.

Propiedad

Descripción

Source

Esta propiedad se utiliza para establecer el origen en una instancia de un objeto. Si no necesita la funcionalidad de establecer un ámbito en el que varias propiedades hereden el mismo contexto de datos, puede utilizar la propiedad Source en lugar de la propiedad DataContext. Para obtener más información, consulte Source.

RelativeSource

Resulta útil si desea especificar el origen con relación a la ubicación donde se encuentra el destino de enlace. Algunos escenarios comunes donde puede utilizar esta propiedad son aquéllos en los que desea enlazar una propiedad del elemento a otra propiedad del mismo elemento o en los que se define un enlace en un estilo o una plantilla. Para obtener más información, consulte RelativeSource.

ElementName

Especifica una cadena que representa el elemento que se desea enlazar. Resulta útil si desear enlazar la propiedad de otro elemento de la aplicación. Por ejemplo, si desea utilizar un control Slider para controlar el alto de otro control de la aplicación, o si desea enlazar la propiedad Content del control a la propiedad SelectedValue del control ListBox. Para obtener más información, consulte ElementName.

Vea también

Referencia

FrameworkElement.DataContext

FrameworkContentElement.DataContext

Conceptos

Herencia de valores de propiedad

Información general sobre el enlace de datos

Información general sobre declaraciones de enlaces

Otros recursos

Temas "Cómo..." sobre enlace de datos