RelativeSource MarkupExtensionRelativeSource MarkupExtension

指定要在绑定标记扩展中使用的 RelativeSource 绑定源的属性,或设置在 XAML 中建立的 Binding 元素的 RelativeSource 属性。Specifies properties of a RelativeSource binding source, to be used within a Binding Markup Extension, or when setting the RelativeSource property of a Binding element established in XAML.

XAML 特性用法XAML Attribute Usage

<Binding RelativeSource="{RelativeSource modeEnumValue}" .../>

XAML 属性用法(嵌套在 Binding 扩展内)XAML Attribute Usage (nested within Binding extension)

<object property="{Binding RelativeSource={RelativeSource modeEnumValue} ...}" .../>

XAML 对象元素用法XAML Object Element Usage

<Binding>
  <Binding.RelativeSource>
    <RelativeSource Mode="modeEnumValue"/>
  </Binding.RelativeSource>
</Binding>

-or-

<Binding>
  <Binding.RelativeSource>
    <RelativeSource
      Mode="FindAncestor"
      AncestorType="{x:Type typeName}"
      AncestorLevel="intLevel"
    />
  </Binding.RelativeSource>
</Binding>

XAML 值XAML Values

modeEnumValue 下列情况之一:One of the following:

-字符串标记 Self;对应于 Mode 属性设置为 Self创建的 RelativeSource- The string token Self; corresponds to a RelativeSource as created with its Mode property set to Self.
-字符串标记 TemplatedParent;对应于 Mode 属性设置为 TemplatedParent创建的 RelativeSource- The string token TemplatedParent; corresponds to a RelativeSource as created with its Mode property set to TemplatedParent.
-字符串标记 PreviousData;对应于 Mode 属性设置为 PreviousData创建的 RelativeSource- The string token PreviousData; corresponds to a RelativeSource as created with its Mode property set to PreviousData.
-有关 FindAncestor 模式的信息,请参阅下文。- See below for information on FindAncestor mode.
FindAncestor 字符串标记 FindAncestorThe string token FindAncestor. 使用此标记可输入一个模式,以便 RelativeSource 指定上级类型和可选的上级级别。Using this token enters a mode whereby a RelativeSource specifies an ancestor type and optionally an ancestor level. 它对应于通过将 RelativeSource 属性设置为 Mode 而创建的 FindAncestorThis corresponds to a RelativeSource as created with its Mode property set to FindAncestor.
typeName 对于 FindAncestor 模式是必需的。Required for FindAncestor mode. 类型的名称,用于填充 AncestorType 属性。The name of a type, which fills the AncestorType property.
intLevel 对于 FindAncestor 模式是可选的。Optional for FindAncestor mode. 上级级别(在逻辑树中向父级方向计算)。An ancestor level (evaluated towards the parent direction in the logical tree).

备注Remarks

{RelativeSource TemplatedParent} 绑定使用情况是一项关键技术,可解决控件的 UI 与控件的逻辑之间的更大分离。{RelativeSource TemplatedParent} binding usages are a key technique that addresses a larger concept of the separation of a control's UI and a control's logic. 这可以实现从模板定义内绑定到模板化父级(在其中应用模板的运行时对象实例)。This enables binding from within the template definition to the templated parent (the run time object instance where the template is applied). 对于这种情况, TemplateBinding 标记扩展实际上是以下绑定表达式的简写: {Binding RelativeSource={RelativeSource TemplatedParent}}For this case, the TemplateBinding Markup Extension is in fact a shorthand for the following binding expression: {Binding RelativeSource={RelativeSource TemplatedParent}}. TemplateBinding{RelativeSource TemplatedParent} 用法仅在定义模板的 XAML 中相关。TemplateBinding or {RelativeSource TemplatedParent} usages are both only relevant within the XAML that defines a template. 有关详细信息,请参阅TemplateBinding 标记扩展For more information, see TemplateBinding Markup Extension.

{RelativeSource FindAncestor} 主要用于控件模板或可预测的自包含 UI 组合,适用于控件始终应位于特定上级类型的可视化树中的情况。{RelativeSource FindAncestor} is mainly used in control templates or predictable self-contained UI compositions, for cases where a control is always expected to be in a visual tree of a certain ancestor type. 例如,项控件的项可能使用 FindAncestor 用法绑定到其项控件父级/祖先级。For example, items of an items control might use FindAncestor usages to bind to properties of their items control parent ancestor. 或者,属于模板中控件组合一部分的元素可使用 FindAncestor 绑定到同一组合结构中的父元素。Or, elements that are part of control composition in a template can use FindAncestor bindings to the parent elements in that same composition structure.

在 XAML 语法章节显示的 FindAncestor 模式的对象元素语法中,第二个对象元素语法专门用于 FindAncestor 模式。In the object element syntax for FindAncestor mode shown in the XAML Syntax sections, the second object element syntax is used specifically for FindAncestor mode. FindAncestor 模式需要 AncestorType 值。FindAncestor mode requires an AncestorType value. 必须将 AncestorType 设置为一个属性,该属性使用对要查找的上级类型的X:Type 标记扩展引用。You must set AncestorType as an attribute using an x:Type Markup Extension reference to the type of ancestor to look for. 当在运行时处理绑定请求时,将会用到 AncestorType 值。The AncestorType value is used when the binding request is processed at run-time.

对于 FindAncestor 模式,当元素树中可能存在多个该类型的上级时,可以使用可选属性 AncestorLevel 帮助消除上级查找的歧义。For FindAncestor mode, the optional property AncestorLevel can help disambiguate the ancestor lookup in cases where there is possibly more than one ancestor of that type existing in the element tree.

有关如何使用 FindAncestor 模式的详细信息,请参阅 RelativeSourceFor more information on how to use the FindAncestor mode, see RelativeSource.

如果实例的一个属性应依赖于同一个实例的另一个属性的值,并且这两个属性之间已存在常规依赖属性关系(如强制),则 {RelativeSource Self} 适用于这种情况。{RelativeSource Self} is useful for scenarios where one property of an instance should depend on the value of another property of the same instance, and no general dependency property relationship (such as coercion) already exists between those two properties. 尽管对象很少存在两个属性,以便这些值按原义相同(并且类型相同),但也可以将 Converter 参数应用到具有 {RelativeSource Self}的绑定,并使用转换器在源和目标类型之间进行转换。Although it is rare that two properties exist on an object such that the values are literally identical (and are identically typed), you can also apply a Converter parameter to a binding that has {RelativeSource Self}, and use the converter to convert between source and target types. {RelativeSource Self} 的另一种情况是作为 MultiDataTrigger的一部分。Another scenario for {RelativeSource Self} is as part of a MultiDataTrigger.

例如,以下 XAML 定义了一个 Rectangle 元素,以便无论为 Width 输入什么值,都确保 Rectangle 始终是一个方形:<Rectangle Width="200" Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}" .../>For example, the following XAML defines a Rectangle element such that no matter what value is entered for Width, the Rectangle is always a square: <Rectangle Width="200" Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}" .../>

{RelativeSource PreviousData} 在数据模板中或在绑定使用集合作为数据源的情况下很有用。{RelativeSource PreviousData} is useful either in data templates, or in cases where bindings are using a collection as the data source. 您可以使用 {RelativeSource PreviousData} 突出显示集合中相邻数据项之间的关系。You can use {RelativeSource PreviousData} to highlight relationships between adjacent data items in the collection. 相关技术是在数据源中的当前项和前一个项之间建立 MultiBinding,并使用此绑定上的转换器来确定这两个项及其属性的差异。A related technique is to establish a MultiBinding between the current and previous items in the data source, and use a converter on that binding to determine the difference between the two items and their properties.

在下面的示例中,项目模板中的第一个 TextBlock 可显示当前编号。In the following example, the first TextBlock in the items template displays the current number. 第二个 TextBlock 绑定是一个 MultiBinding,通常具有两个 Binding 要素:当前记录和通过使用 {RelativeSource PreviousData}有意使用以前的数据记录的绑定。The second TextBlock binding is a MultiBinding that nominally has two Binding constituents: the current record, and a binding that deliberately uses the previous data record by using {RelativeSource PreviousData}. 然后,MultiBinding 上的转换器将计算差异,并将其返回到绑定。Then, a converter on the MultiBinding calculates the difference and returns it to the binding.

<ListBox Name="fibolist">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding}"/>
            <TextBlock>, difference = </TextBlock>
                <TextBlock>
                    <TextBlock.Text>
                        <MultiBinding Converter="{StaticResource DiffConverter}">
                            <Binding/>
                            <Binding RelativeSource="{RelativeSource PreviousData}"/>
                        </MultiBinding>
                    </TextBlock.Text>
                </TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>

此处未介绍如何将数据绑定描述为概念,请参阅数据绑定概述Describing data binding as a concept is not covered here, see Data Binding Overview.

WPFWPF XAML 处理器实现中,对此标记扩展的处理由 RelativeSource 类定义。In the WPFWPF XAML processor implementation, the handling for this markup extension is defined by the RelativeSource class.

RelativeSource 是标记扩展。RelativeSource is a markup extension. 当要求转义特性值应为非文本值或非处理程序名称时,通常会实现标记扩展,相对于只在某些类型或属性上放置类型转换器而言,此需求更具有全局性。Markup extensions are typically implemented when there is a requirement to escape attribute values to be other than literal values or handler names, and the requirement is more global than just putting type converters on certain types or properties. XAML 中的所有标记扩展在其特性语法中使用 {} 字符,这是 XAML 处理器识别标记扩展必须处理特性的约定。All markup extensions in XAML use the { and } characters in their attribute syntax, which is the convention by which a XAML processor recognizes that a markup extension must process the attribute. 有关详细信息,请参阅标记扩展和 WPF XAMLFor more information, see Markup Extensions and WPF XAML.

另请参阅See also