{Binding} 標記延伸{Binding} markup extension

注意

新的系結機制適用于 Windows 10,可針對效能和開發人員生產力進行優化。A new binding mechanism is available for Windows 10, which is optimized for performance and developer productivity. 請參閱 {x:Bind} 標記延伸See {x:Bind} markup extension.

注意

如需有關在您的應用程式中搭配 {binding} 使用資料系結的一般資訊 (以及 {X:Bind}{binding}) 之間的整體比較,請參閱 深入資料系結。For general info about using data binding in your app with {Binding} (and for an all-up comparison between {x:Bind} and {Binding}), see Data binding in depth.

{Binding} 標記延伸是用來將控制項上的屬性系結至來自資料來源(例如程式碼)的值。The {Binding} markup extension is used to data bind properties on controls to values coming from a data source such as code. {Binding} 標記延伸會在 XAML 載入時間轉換成 Binding 類別的執行個體。The {Binding} markup extension is converted at XAML load time into an instance of the Binding class. 這個繫結物件會取得資料來源上的屬性值,並推送至控制項上的屬性。This binding object gets a value from a property on a data source, and pushes it to the property on the control. 您可以選擇性地設定繫結物件,以便觀察資料來源屬性值的變更,並根據這些變更對它做出更新。The binding object can optionally be configured to observe changes in the value of the data source property and update itself based on those changes. 您也可以選擇性地設定繫結物件,以便將控制項值中的變更推回到來源屬性。It can also optionally be configured to push changes to the control value back to the source property. 做為資料繫結目標的屬性必須是相依性屬性。The property that is the target of a data binding must be a dependency property. 如需詳細資訊,請參閱相依性屬性概觀For more info, see Dependency properties overview.

{Binding} 具有與本機值相同的相依性屬性優先順序,並且在命令式程式碼中設定本機值將會移除標記中任何 {Binding} 設定的效果。{Binding} has the same dependency property precedence as a local value, and setting a local value in imperative code removes the effect of any {Binding} set in markup.

XAML 屬性用法XAML attribute usage

<object property="{Binding}" .../>
-or-
<object property="{Binding propertyPath}" .../>
-or-
<object property="{Binding bindingProperties}" .../>
-or-
<object property="{Binding propertyPath, bindingProperties}" .../>
詞彙Term 描述Description
propertyPathpropertyPath 指定繫結屬性路徑的字串。A string that specifies the property path for the binding. 如需詳細資訊,請參閱下面屬性路徑一節。More info is in the Property path section below.
bindingPropertiesbindingProperties propName =value [ 、 propName = ]*propName=value[, propName=value]*
使用名稱/值對語法指定的一或多個繫結屬性。One or more binding properties that are specified using a name/value pair syntax.
propNamepropName 在系結物件上 設定之屬性的字串名稱。The string name of the property to set on the Binding object. 例如,"Converter"。For example, "Converter".
valuevalue 設定屬性使用的值。The value to set the property to. 引數的語法取決於下面可以使用 {Binding} 設定的繫結類別屬性一節的屬性。The syntax of the argument depends on the property of Properties of the Binding class that can be set with {Binding} section below.

屬性路徑Property path

路徑說明您繫結的屬性 (來源屬性)。Path describes the property that you're binding to (the source property). 路徑是一個位置參數,表示您可以明確使用參數名稱 ({Binding Path=EmployeeID}),或者您可以將它指定為第一個未命名參數 ({Binding EmployeeID})。Path is a positional parameter, which means you can use the parameter name explicitly ({Binding Path=EmployeeID}), or you can specify it as the first unnamed parameter ({Binding EmployeeID}).

Path 的類型是屬性路徑,它是自訂類型或架構類型之屬性或子屬性的評估字串。The type of Path is a property path, which is a string that evaluates to a property or sub-property of either your custom type or a framework type. 類型可以是 (但不一定要是) DependencyObjectThe type can be, but does not need to be, a DependencyObject. 屬性路徑中的步驟會使用句點 (.) 隔開,您可以納入多個分隔符號來周遊連續的子屬性。Steps in a property path are delimited by dots (.), and you can include multiple delimiters to traverse successive sub-properties. 使用句點分隔符號,無論用來實作繫結目標物件的程式設計語言為何。Use the dot delimiter regardless of the programming language used to implement the object being bound to.

例如,若要將 UI 繫結到員工物件的名字屬性,則您的屬性路徑可能會是 "Employee.FirstName"。For example, to bind UI to an employee object's first name property, your property path might be "Employee.FirstName". 如果您是要將項目控制項繫結到包含員工相依項的屬性,則您的屬性路徑可能會是 "Employee.Dependents",而項目控制項的項目範本會負責顯示 "Dependents" 中的項目。If you are binding an items control to a property that contains an employee's dependents, your property path might be "Employee.Dependents", and the item template of the items control would take care of displaying the items in "Dependents".

如果資料來源是一個集合,則屬性路徑可以依據項目的位置或索引來指定集合中的項目。If the data source is a collection, then a property path can specify items in the collection by their position or index. 例如,「團隊 [ 0」 ] 。「播放程式」,其中常值 " [ ] " 會括住 "0",以指定集合中的第一個專案。For example, "Teams[0].Players", where the literal "[]" encloses the "0" that specifies the first item in a collection.

使用繫結到現有 DependencyObjectElementName 時,可以使用附加屬性做為屬性路徑的一部分。When using an ElementName binding to an existing DependencyObject, you can use attached properties as part of the property path. 為使附加屬性的意義清楚,讓附加屬性名稱中間的點不會被視為屬性路徑的步驟,請使用括號括住擁有者限定的附加屬性名稱;例如,(AutomationProperties.Name)To disambiguate an attached property so that the intermediate dot in the attached property name is not considered a step into a property path, put parentheses around the owner-qualified attached property name; for example, (AutomationProperties.Name).

屬性路徑中繼物件會儲存為執行階段表示法中的 PropertyPath 物件,但是大部分案例都不需要與程式碼中的 PropertyPath 物件互動。A property path intermediate object is stored as a PropertyPath object in a run-time representation, but most scenarios won't need to interact with a PropertyPath object in code. 您通常可以使用 XAML 來指定所需的繫結資訊。You can usually specify the binding info you need using XAML.

如需屬性路徑的字串語法、動畫功能區域中的屬性路徑以及建構 PropertyPath 物件的詳細資訊,請參閱 Property-path 語法For more info about the string syntax for a property path, property paths in animation feature areas, and constructing a PropertyPath object, see Property-path syntax.

可以使用 {Binding} 設定的繫結類別屬性Properties of the Binding class that can be set with {Binding}

{Binding}bindingProperties 預留位置語法進行說明,因為在標記延伸中可以設定 Binding 的多個讀取/寫入屬性。{Binding} is illustrated with the bindingProperties placeholder syntax because there are multiple read/write properties of a Binding that can be set in the markup extension. 您可以使用以逗號分隔的propName值組,以任何順序設定屬性 = valueThe properties can be set in any order with comma-separated propName=value pairs. 某些屬性需要不具類型轉換的類型,因此這些屬性需要將自己的標記延伸巢狀在 {Binding} 內。Some of the properties require types that don't have a type conversion, so these require markup extensions of their own nested within the {Binding}.

屬性Property 說明Description
路徑Path 請參閱先前的屬性路徑一節。See the Property path section above.
ConverterConverter 指定繫結引擎呼叫的轉換器物件。Specifies a converter object that is called by the binding engine. 轉換器可以使用 {StaticResource} 標記延伸在標記中設定,以參考至資源字典中的該物件。The converter can be set in markup using the {StaticResource} markup extension to reference to that object from a resource dictionary.
ConverterLanguageConverterLanguage 指定轉換器要使用的文化特性Specifies the culture to be used by the converter. (若您要設定 Converter)。文化特性可以設定為標準式識別碼。(If you're setting Converter.) The culture is set as a standards-based identifier. 如需詳細資訊,請參閱 ConverterLanguageFor more info, see ConverterLanguage
ConverterParameterConverterParameter 指定可用於轉換器邏輯的轉換器參數。Specifies a converter parameter that can be used in converter logic. (如果您要設定 Converter)。大多數轉換器都可以使用簡單邏輯,從傳遞的值中取得所需的所有資訊進行轉換,而且不需要 ConverterParameter 值。(If you're setting Converter.) Most converters use simple logic that get all the info they need from the passed value to convert, and don't need a ConverterParameter value. ConverterParameter 參數適用於更為複雜的轉換器實作,這些實作具備可切斷 ConverterParameter 中傳遞之內容的條件式邏輯。The ConverterParameter parameter is for more complex converter implementations that have conditional logic that keys off what's passed in ConverterParameter. 您可以撰寫一個使用字串以外的值的轉換器,但這並不常見,請參閱 ConverterParameter 中的<備註>,以了解詳細資訊。You can write a converter that uses values other than strings but this is uncommon, see Remarks in ConverterParameter for more info.
ElementNameElementName 透過參考相同 XAML 建構中具有 Name 屬性或 x:Name 屬性的另一個元素來指定資料來源。Specifies a data source by referencing another element in the same XAML construct that has a Name property or x:Name attribute. 這通常是用來共用相關的值,或使用一個 UI 元素的子屬性提供特定值給另一個元素 (例如,在 XAML 控制項範本中)。This is often use to share related values or use sub-properties of one UI element to provide a specific value for another element, for example in a XAML control template.
FallbackValueFallbackValue 指定當無法解析來源或路徑時,所要顯示的值。Specifies a value to display when the source or path cannot be resolved.
[模式]Mode 指定繫結模式,如下列其中一值:"OneTime"、"OneWay" 或 "TwoWay"。Specifies the binding mode, as one of these values: "OneTime", "OneWay", or "TwoWay". 這些會對應 BindingMode 列舉的常數名稱。These correspond to the constant names of the BindingMode enumeration. 預設值是 "OneWay"。The default is "OneWay". 請注意,這與 {x:Bind} 的預設值 ("OneTime") 不同。Note that this differs from the default for {x:Bind}, which is "OneTime".
RelativeSourceRelativeSource 透過描述相對於繫結目標位置的繫結來源位置,以指定資料來源。Specifies a data source by describing the position of the binding source relative to the position of the binding target. 這最常用於 XAML 控制項範本內的繫結中。This is most often used in bindings within XAML control templates. 設定 {RelativeSource} 標記延伸Setting the {RelativeSource} markup extension.
來源Source 指定物件資料來源。Specifies the object data source. Binding 標記延伸內,Source 屬性需要物件參考,例如 {StaticResource} 標記延伸參考。Within the Binding markup extension, the Source property requires an object reference, such as a {StaticResource} markup extension reference. 如果未指定這個屬性,動作資料內容會指定來源。If this property is not specified, the acting data context specifies the source. 通常不會在個別的繫結中指定 Source 值,而是倚賴共用的 DataContext 進行多重繫結。It's more typical to not specify a Source value in individual bindings, and instead to rely on the shared DataContext for multiple bindings. 如需詳細資訊,請參閱DataContext深入了解資料繫結For more info see DataContext or Data binding in depth.
TargetNullValueTargetNullValue 指定當來源值解析結果明確為 null 時,所要顯示的值。Specifies a value to display when the source value resolves but is explicitly null.
UpdateSourceTriggerUpdateSourceTrigger 指定繫結來源更新的時機。Specifies the timing of binding source updates. 如果沒有指定,則預設為 DefaultIf unspecified, the default is Default.

注意   如果您要將標記從 {x:Bind} 轉換成 {Binding},請注意Mode屬性之預設值的差異。Note  If you're converting markup from {x:Bind} to {Binding}, then be aware of the differences in default values for the Mode property.

ConverterConverterLanguageConverterLanguage 皆與來自繫結來源的值或類型轉換成和繫結目標屬性相容的類型或值的案例相關。Converter, ConverterLanguage and ConverterLanguage are all related to the scenario of converting a value or type from the binding source into a type or value that is compatible with the binding target property. 如需詳細資訊和範例,請參閱深入了解資料繫結中的<資料轉換>一節。For more info and examples, see the "Data conversions" section of Data binding in depth.

注意

從 Windows 10 版本 1607 開始,XAML 架構針對可見度轉換器提供了內建布林值。Starting in Windows 10, version 1607, the XAML framework provides a built in Boolean to Visibility converter. 轉換器會將 true 對應至 可見 的列舉值,並將 false 轉換成折迭,如此您 就可以在不建立轉換器的情況下,將可見度屬性系結至布林值。The converter maps true to the Visible enumeration value and false to Collapsed so you can bind a Visibility property to a Boolean without creating a converter. 若要使用內建轉換器,您 App 的最低目標 SDK 版本必須為 14393 或更新版本。To use the built in converter, your app's minimum target SDK version must be 14393 or later. 當您的 App 是以舊版 Windows 10 為目標時,您就無法使用它。You can't use it when your app targets earlier versions of Windows 10. 如需目標版本的相關詳細資訊,請參閱版本調適型程式碼For more info about target versions, see Version adaptive code.

SourceRelativeSourceElementName 都可以指定繫結來源,因此彼此互斥。Source, RelativeSource, and ElementName specify a binding source, so they are mutually exclusive.

秘訣   如果您需要為值指定單一大括弧(例如在PathConverterParameter中),請在其前面加上反斜線: \{Tip  If you need to specify a single curly brace for a value, such as in Path or ConverterParameter, then precede it with a backslash: \{. 或者,將整個字串括起來,以包含需要在設定的第二個引號中逸出的括號,例如 ConverterParameter='{Mix}'Alternatively, enclose the entire string that contains the braces that need escaping in a secondary quotation set, for example ConverterParameter='{Mix}'.

範例Examples

<!-- binding a UI element to a view model -->    
<Page ... >
    <Page.DataContext>
        <local:BookstoreViewModel/>
    </Page.DataContext>

    <GridView ItemsSource="{Binding BookSkus}" SelectedItem="{Binding SelectedBookSku, Mode=TwoWay}" ... />
</Page>
<!-- binding a UI element to another UI element -->
<Page ... >
    <Page.Resources>
        <local:S2Formatter x:Key="GradeConverter"/>
    </Page.Resources>

    <Slider x:Name="sliderValueConverter" ... />
    <TextBox Text="{Binding Path=Value, ElementName=sliderValueConverter,
        Mode=OneWay,
        Converter={StaticResource GradeConverter}}"/>
</Page>

第二個範例設定了四個不同的 Binding 屬性:ElementNamePathModeConverterThe second example sets four different Binding properties: ElementName, Path, Mode and Converter. Path 在此例中顯示明確命名為 Binding 屬性。Path in this case is shown explicitly named as a Binding property. Path 被評估為資料繫結來源,這個來源是相同執行階段物件樹中的另一個物件 (一個名稱為 sliderValueConverterSlider)。The Path is evaluated to a data binding source that is another object in the same run-time object tree, a Slider named sliderValueConverter.

請注意 Converter 屬性值如何使用另一個標記延伸 ({StaticResource} 標記延伸),因此這裡使用了兩個巢狀標記延伸。Note how the Converter property value uses another markup extension, {StaticResource} markup extension, so there are two nested markup extension usages here. 內部的標記延伸會先進行評估,因此一旦取得資源之後,就會有一個可供繫結使用的實用 IValueConverter (由資源中的 local:S2Formatter 元素所具現化的自訂類別)。The inner one is evaluated first, so that once the resource is obtained there's a practical IValueConverter (a custom class that's instantiated by the local:S2Formatter element in resources) that the binding can use.

工具支援Tools support

在 XAML 標記編輯器中撰寫 {Binding} 時,Microsoft Visual Studio 中的 Microsoft IntelliSense 會顯示資料內容的屬性。Microsoft IntelliSense in Microsoft Visual Studio displays the properties of the data context while authoring {Binding} in the XAML markup editor. 在您輸入 "{Binding" 後,適用於 Path 的資料內容屬性即會顯示在下拉式清單中。As soon as you type "{Binding", data context properties appropriate for Path are displayed in the dropdown. IntelliSense 也可協助 Binding 的其他屬性。IntelliSense also helps with the other properties of Binding. 若要讓此功能運作,您必須在標記頁面中設定資料內容或設計階段資料內容。For this to work, you must have either the data context or the design-time data context set in the markup page. 移至定義 (F12) 也可以用於 {Binding}Go To Definition (F12) also works with {Binding}. 另一種方法是使用資料繫結對話方塊。Alternatively, you can use the data binding dialog.