RelativeSource 標記延伸RelativeSource MarkupExtension

指定的屬性RelativeSource繫結來源,使用於繫結標記延伸,或設定時RelativeSource屬性Binding在 XAML 中建立的項目。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 Attribute UsageXAML 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; 對應至RelativeSource建立其Mode屬性設定為Self- The string token Self; corresponds to a RelativeSource as created with its Mode property set to Self.
-字串語彙基元TemplatedParent; 對應至RelativeSource建立其Mode屬性設定為TemplatedParent- The string token TemplatedParent; corresponds to a RelativeSource as created with its Mode property set to TemplatedParent.
-字串語彙基元PreviousData; 對應至RelativeSource建立其Mode屬性設定為PreviousData- 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}的一部分是MultiDataTriggerAnother 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. 如果必須將屬性 (Attribute) 值加上逸出符號,以免成為常值或處理常式名稱,而且這個動作必須更全面地實施 (而不是只對特定類型或屬性 (Property) 設定類型轉換子 (Type Converter)),則通常會實作標記延伸。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