通过


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在命名空间中SDKSample定义的PersonName字符串属性的对象,如第一个突出显示的行所示。 在包含元素的<src>突出显示行中,它将对象PersonName实例化Person属性值为 .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”。

在以下示例中,对象的 SourceBinding 设置为 static 属性 Application.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.RelativeSource属性Binding.ElementName还允许显式设置绑定的源。 但是,应为每个绑定设置三个属性中的ElementNameSourceRelativeSource一个,或者可能发生冲突。 如果存在绑定源冲突,此属性将引发异常。

若要清除此属性,请将其设置为 DependencyProperty.UnsetValue.

XAML 属性用法

<object Source="object"/>

XAML 值

对象 现有对象。 若要引用现有对象,请使用 StaticResource 标记扩展

适用于