共用方式為


Binding.Source 屬性

定義

取得或設定物件作為綁定來源。

public:
 property System::Object ^ Source { System::Object ^ get(); void set(System::Object ^ value); };
public object Source { get; set; }
member this.Source : obj with get, set
Public Property Source As Object

屬性值

作為束縛源的物件。

範例

以下範例使用 Person 一個具有字 PersonName 串屬性的物件,該屬性定義於 SDKSample 命名空間中,如第一行標示所示。 在包含該 <src> 元素的標示行中,物件實 Person 例化的 PersonName 屬性值為 Joe。 此操作在 Resources 該區段執行,並賦予 x:Key

<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>

包含 <TextBlock> 元素的高亮線顯示如何綁定該 PersonName 屬性。 因此, TextBlock 控制點會顯示為「Joe」。

在以下範例中,Source物件的Binding值被設定為屬性staticApplication.Current

<ComboBox.IsEnabled>
    <MultiBinding Converter="{StaticResource specialFeaturesConverter}">
        <Binding Path="CurrentUser.Rating" 
          Source="{x:Static Application.Current}"/>
        <Binding Path="CurrentUser.MemberSince" 
    Source="{x:Static Application.Current}"/>
    </MultiBinding>
</ComboBox.IsEnabled>

備註

預設情況下,綁定會繼承屬性 DataContext 所指定的資料上下文(若已設定)。 不過,這個 Source 屬性是你可以明確設定 來源 Binding 並覆寫繼承資料上下文的方法之一。 如果你不需要建立一個讓多個屬性繼承相同資料上下文的範圍功能,你可以用這個 Source 屬性代替屬性 DataContext

Binding.ElementNameBinding.RelativeSource 屬性也讓你能明確設定綁定的來源。 然而,每個綁定的三個性質 ElementName中,只有 、 SourceRelativeSource和 ,否則可能會發生衝突。 此特性若存在約束性來源衝突,會拋出例外。

要清除此屬性,請將其設為 DependencyProperty.UnsetValue

XAML 屬性使用方式

<object Source="object"/>

XAML 值

目的 一個存在的物件。 若要參考現有物件,請使用 StaticResource Markup 擴充功能

適用於