Binding.RelativeSource 属性

定义

通过指定绑定源相对于绑定目标位置的位置,获取或设置此绑定源。Gets or sets the binding source by specifying its location relative to the position of the binding target.

public:
 property System::Windows::Data::RelativeSource ^ RelativeSource { System::Windows::Data::RelativeSource ^ get(); void set(System::Windows::Data::RelativeSource ^ value); };
public System.Windows.Data.RelativeSource RelativeSource { get; set; }
member this.RelativeSource : System.Windows.Data.RelativeSource with get, set
Public Property RelativeSource As RelativeSource

属性值

一个 RelativeSource 对象,它指定要使用的绑定源的相对位置。A RelativeSource object specifying the relative location of the binding source to use. 默认值为 nullThe default is null.

示例

下面的示例演示一个用于创建报表验证错误消息的 ToolTip 的样式触发器。The following example shows a style trigger that creates a ToolTip that reports a validation error message. Setter 的值使用 RelativeSource 属性绑定到当前 TextBox (使用样式的 TextBox)的错误内容。The value of the setter binds to the error content of the current TextBox (the TextBox using the style) using the RelativeSource property. 有关此示例的详细信息,请参阅如何:实现绑定验证For more information on this example, see How to: Implement Binding Validation.

<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}">
  <Style.Triggers>
    <Trigger Property="Validation.HasError" Value="true">
      <Setter Property="ToolTip"
        Value="{Binding RelativeSource={x:Static RelativeSource.Self},
                        Path=(Validation.Errors)/ErrorContent}"/>
    </Trigger>
  </Style.Triggers>
</Style>

若要查看完整的示例,请参阅绑定验证示例To see the full example, see Binding Validation Sample.

注解

此属性通常用于将对象的一个属性绑定到同一对象的另一个属性,或在样式或模板中定义绑定。This property is commonly used to bind one property of an object to another property of the same object, or to define a binding in a style or template.

默认情况下,绑定将继承 DataContext 属性指定的数据上下文(如果已设置)。By default, bindings inherit the data context specified by the DataContext property, if one has been set. 不过,RelativeSource 属性是您显式设置 Binding 源并重写继承的数据上下文的方式之一。However, the RelativeSource property is one of the ways you can explicitly set the source of a Binding and override the inherited data context. 有关详细信息,请参阅如何:指定绑定源For more information, see How to: Specify the Binding Source.

使用 "Binding.ElementName" 和 "Binding.Source" 属性,还可以显式设置绑定的源。The Binding.ElementName and Binding.Source properties also enable you to set the source of the binding explicitly. 但是,只应为每个绑定设置三个属性中的一个(ElementNameSourceRelativeSource),否则可能会发生冲突。However, only one of the three properties, ElementName, Source, and RelativeSource, should be set for each binding, or a conflict can occur. 如果存在绑定源冲突,则此属性将引发异常。This property throws an exception if there is a binding source conflict.

有关 XAMLXAML 的信息,请参阅RelativeSource MarkupExtensionFor XAMLXAML information, see RelativeSource MarkupExtension.

适用于

另请参阅