방법: 바인딩 소스 지정

데이터 바인딩에서 바인딩 소스 개체는 데이터를 가져온 개체를 참조합니다. 이 항목에서는 바인딩 소스를 지정하는 여러 가지 방법을 설명합니다.

예제

하나의 공용 소스에 여러 개의 속성을 바인딩하는 경우 DataContext 속성을 사용할 수 있습니다. 이 속성은 모든 데이터 바인딩된 속성이 공용 소스를 상속받게 되는 범위를 설정하는 편리한 방법을 제공합니다.

다음 예제에서 데이터 컨텍스트는 애플리케이션의 루트 요소에 설정됩니다. 따라서 모든 자식 요소가 해당 데이터 컨텍스트를 상속받을 수 있습니다. 바인딩할 데이터는 사용자 지정 데이터 클래스, 즉 매핑과 incomeDataSource의 지정한 리소스 키를 통해 직접 참조되는 NetIncome에서 옵니다.

<Grid
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://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>

다음 예제에서는 NetIncome 클래스의 정의를 보여 줍니다.

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));
        }
    }
}
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

참고

위의 예제는 태그에서 개체를 인스턴스화하며 개체를 리소스로 사용합니다. 코드에서 이미 인스턴스화된 개체에 바인딩하려는 경우 DataContext 속성을 프로그래밍 방식으로 설정해야 합니다. 예제는 XAML의 바인딩에 사용할 수 있는 데이터 만들기를 참조하세요.

또는 개별 바인딩에서 소스를 명시적으로 지정하려는 경우 다음 옵션을 사용할 수 있습니다. 이러한 옵션은 상속된 데이터 컨텍스트보다 우선합니다.

속성 설명
Source 이 속성을 사용하여 소스를 개체의 인스턴스로 설정합니다. 여러 속성이 같은 데이터 컨텍스트를 상속받는 범위를 설정하는 기능이 필요하지 않은 경우 DataContext 속성 대신 Source 속성을 사용할 수 있습니다. 자세한 내용은 Source를 참조하세요.
RelativeSource 이는 바인딩 대상이 있는 위치와 상대적인 소스를 지정할 때 유용합니다. 이 속성을 사용할 수 있는 몇 가지 일반 시나리오 중 요소의 한 속성을 같은 요소의 다른 속성에 바인딩하거나 스타일 또는 템플릿에서 바인딩을 정의하는 경우가 이에 해당합니다. 자세한 내용은 RelativeSource를 참조하세요.
ElementName 바인딩할 요소를 나타내는 문자열을 지정합니다. 이는 애플리케이션에서 다른 요소의 속성에 바인딩하려고 할 때 유용합니다. 예를 들어 사용 하려는 경우를 Slider 애플리케이션에서 다른 컨트롤의 높이 제어 하 바인딩하려는 경우 또는 Content 컨트롤을 SelectedValue 의 속성에 ListBox 컨트롤. 자세한 내용은 ElementName를 참조하세요.

참조