操作說明:指定繫結來源

在資料繫結中,繫結來源物件是指您的資料取得來源物件。 本主題說明指定繫結來源的不同方式。

範例

如果您將數個屬性繫結至同一個來源,要使用 DataContext 屬性,它是建立範圍的便利方式,在這個範圍中所有資料繫結屬性都繼承同一個來源。

下列範例會在應用程式的根元素建立資料內容。 這會使所有子元素都繼承這個資料內容。 繫結的資料來自自訂的資料類別 NetIncome,這個類別是直接透過對應來參考,並且具有資源索引鍵 incomeDataSource

<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 使用這個屬性將來源設定為物件的執行個體。 如果您不需要建立範圍的功能,其中的數個屬性會繼承相同的資料內容,您可以使用 Source 屬性,而不是 DataContext 屬性。 如需詳細資訊,請參閱Source
RelativeSource 當您想以相對於繫結目標的位置指定來源,這十分有用。 使用這個屬性的常見案例是,當您想將元素的一個屬性繫結至同一元素的其他屬性時,或當您正在樣式或範本中定義繫結時。 如需詳細資訊,請參閱RelativeSource
ElementName 指定一個字串來代表您想繫結至的元素。 當您想要繫結至應用程式中其他元素的屬性時,這十分有用。 例如,如果您想要使用 Slider 來控制應用程式中另一個控制項的高度,或您想要將 控制項的 系結 ContentSelectedValue 控制項的 ListBox 屬性。 如需詳細資訊,請參閱ElementName

另請參閱