相依性屬性概觀Dependency properties overview

這個主題說明當您使用 C++、C# 或 Visual Basic 搭配 UI 的 XAML 定義來撰寫 Windows 執行階段應用程式時,可供使用的相依性屬性系統。This topic explains the dependency property system that is available when you write a Windows Runtime app using C++, C#, or Visual Basic along with XAML definitions for UI.

什麼是相依性屬性?What is a dependency property?

相依性屬性是特殊化的屬性類型。A dependency property is a specialized type of property. 更明確地說,這個屬性會追蹤屬性值,並受到專用屬性系統 (Windows 執行階段的一部分) 所影響。Specifically it's a property where the property's value is tracked and influenced by a dedicated property system that is part of the Windows Runtime.

為了支援相依性屬性,定義屬性的物件必須是 DependencyObject (也就是在其繼承中包含了 DependencyObject 基底類別的類別)。In order to support a dependency property, the object that defines the property must be a DependencyObject (in other words a class that has the DependencyObject base class somewhere in its inheritance). 許多您針對 UWP 應用程式的 UI 定義使用 XAML 的型別都是 DependencyObject 子類別,並且將支援相依性屬性。Many of the types you use for your UI definitions for a UWP app with XAML will be a DependencyObject subclass, and will support dependency properties. 但是,任何來自其名稱內不含 "XAML" 的 Windows 執行階段命名空間的類型將不支援相依性屬性;這類型的屬性是一般屬性,將不會擁有屬性系統的相依性行為。However, any type that comes from a Windows Runtime namespace that doesn't have "XAML" in its name won't support dependency properties; properties of such types are ordinary properties that won't have the property system's dependency behavior.

相依性屬性的目的是提供一個系統方法,以根據其他輸入 (當您的 app 執行時,於該應用程式內發生的其他屬性、事件及狀態) 來計算屬性值。The purpose of dependency properties is to provide a systemic way to compute the value of a property based on other inputs (other properties, events and states that occur within your app while it runs). 這些其他輸入可能包括:These other inputs might include:

  • 外部輸入,如使用者喜好設定External input such as user preference
  • Just-In-Time 屬性判定機制,如資料繫結、動畫及分鏡腳本Just-in-time property determination mechanisms such as data binding, animations and storyboards
  • 多用途範本模式,如資源和樣式Multiple-use templating patterns such as resources and styles
  • 透過與物件樹中其他元素的父系-子系關係取得的值Values known through parent-child relationships with other elements in the object tree

對於 UI 使用 XAML 而程式碼使用 C#、Microsoft Visual Basic 或 Visual C++ 元件延伸 (C++/CX) 定義的 Windows 執行階段應用程式,相依性屬性代表或支援這種程式設計模型的特定功能。A dependency property represents or supports a specific feature of the programming model for defining a Windows Runtime app with XAML for UI and C#, Microsoft Visual Basic or Visual C++ component extensions (C++/CX) for code. 這些功能包括:These features include:

  • 資料繫結Data binding
  • 樣式Styles
  • 腳本動畫Storyboarded animations
  • "PropertyChanged" 行為;可以實作相依性屬性來提供可將變更傳播到其他相依性屬性的回呼"PropertyChanged" behavior; a dependency property can be implemented to provide callbacks that can propagate changes to other dependency properties
  • 使用來自屬性中繼資料的預設值Using a default value that comes from property metadata
  • 一般屬性系統公用程式,像是 ClearValue 與中繼資料查閱General property system utility such as ClearValue and metadata lookup

相依性屬性與 Windows 執行階段屬性Dependency properties and Windows Runtime properties

相依性屬性會藉由提供全域內部屬性儲存區來擴充基本的 Windows 執行階段屬性功能,這個屬性儲存區會在執行階段支援應用程式中的所有相依性屬性。Dependency properties extend basic Windows Runtime property functionality by providing a global, internal property store that backs all of the dependency properties in an app at run time. 這是以私用欄位支援屬性的標準模式替代方案,而私用欄位在屬性定義類別中為私用的。This is an alternative to the standard pattern of backing a property with a private field that's private in the property-definition class. 您可以將這個內部屬性儲存區想像成是為任一特定物件而存在的一組屬性識別碼和值 (只要它是 DependencyObject 即可)。You can think of this internal property store as being a set of property identifiers and values that exist for any particular object (so long as it's a DependencyObject). 儲存區中的每個屬性是由 DependencyProperty 執行個體來識別,而不是由名稱來識別。Rather than being identified by name, each property in the store is identified by a DependencyProperty instance. 但是,屬性系統常會隱藏這個實作詳細資料:您通常可以使用簡單名稱 (程式碼語言中使用的程式設計屬性名稱,或是撰寫 XAML 時使用的屬性名稱) 來存取相依性屬性。However, the property system mostly hides this implementation detail: you can usually access dependency properties by using a simple name (the programmatic property name in the code language you're using, or an attribute name when you're writing XAML).

提供相依性屬性系統基礎的基底類型是 DependencyObjectThe base type that provides the underpinnings of the dependency property system is DependencyObject. DependencyObject 會定義可以存取相依性屬性的方法,而 DependencyObject 衍生類別的執行個體內部支援我們先前提及的屬性儲存區概念。DependencyObject defines methods that can access the dependency property, and instances of a DependencyObject derived class internally support the property store concept we mentioned earlier.

下列是我們在討論相依性屬性時,於文件中所使用的詞彙摘要:Here is a summation of the terminology that we use in the documentation when discussing dependency properties:

詞彙Term 描述Description
相依性屬性Dependency property 存在於 DependencyProperty 識別碼的屬性 (如下所示)。A property that exists on a DependencyProperty identifier (see below). 這個識別碼通常是以負責定義 DependencyObject 衍生類別的靜態成員方式來提供。Usually this identifier is available as a static member of the defining DependencyObject derived class.
相依性屬性識別碼Dependency property identifier 用來識別屬性的常數值,通常是公用和唯讀的。A constant value to identify the property, it is typically public and read-only.
屬性包裝函式Property wrapper Windows 執行階段屬性的可呼叫 getset 實作。The callable get and set implementations for a Windows Runtime property. 或者是原始定義的語言特定投影。Or, the language-specific projection of the original definition. get 屬性包裝函式實作會呼叫 GetValue,傳遞相關的相依性屬性識別碼。A get property wrapper implementation calls GetValue, passing the relevant dependency property identifier.

屬性包裝函式不只對呼叫者方便,也可以向使用 Windows 執行階段屬性定義的任何程序、工具或投影公開相依性屬性。The property wrapper is not just convenience for callers, it also exposes the dependency property to any process, tool or projection that uses Windows Runtime definitions for properties.

下列範例會定義定義給 c # 的自訂相依性屬性,並顯示相依性屬性識別碼與屬性包裝函式的關聯性。The following example defines a custom dependency property as defined for C#, and shows the relationship of the dependency property identifier to the property wrapper.

public static readonly DependencyProperty LabelProperty = DependencyProperty.Register(
  "Label",
  typeof(string),
  typeof(ImageWithLabelControl),
  new PropertyMetadata(null)
);


public string Label
{
    get { return (string)GetValue(LabelProperty); }
    set { SetValue(LabelProperty, value); }
}

注意

上述範例不適合用來做為如何建立自訂相依性屬性的完整範例。The preceding example is not intended as the complete example for how to create a custom dependency property. 而是為了顯示相依性屬性概念,讓使用者藉由程式碼具體了解概念。It is intended to show dependency property concepts for anyone that prefers learning concepts through code. 如需此範例的完整說明,請參閱 自訂相依性屬性。For a more complete explanation of this example, see Custom dependency properties.

相依性屬性值優先順序Dependency property value precedence

當您取得相依性屬性的值時,您所取得的值是透過任一種參與 Windows 執行階段屬性系統的輸入,針對該屬性進行判斷的值。When you get the value of a dependency property, you are obtaining a value that was determined for that property through any one of the inputs that participate in the Windows Runtime property system. 因為有相依性屬性值的優先順序,使得 Windows 執行階段屬性系統可以透過可預期的方式來計算值,而且您也應該熟悉基本優先順序。Dependency property value precedence exists so that the Windows Runtime property system can calculate values in a predictable way, and it's important that you be familiar with the basic precedence order too. 否則,您可能會發現自己處於下列情況中:您正嘗試在某一個優先順序層級上設定屬性,但其他作業 (系統、協力廠商呼叫者、您自己的部分程式碼) 正在其他層級上設定該屬性,而當您嘗試找出使用的是哪個屬性值以及該值是來自何處時感到沮喪。Otherwise, you might find yourself in a situation where you're trying to set a property at one level of precedence but something else (the system, third-party callers, some of your own code) is setting it at another level, and you'll get frustrated trying to figure out which property value is used and where that value came from.

例如,樣式與範本是建立屬性值與控制項外觀的共用起點。For example, styles and templates are intended to be a shared starting point for establishing property values and thus appearances of a control. 但在特定的控制項執行個體中,您可能想變更常見的範本值,例如,為該控制項提供不同的背景色彩或不同的文字字串做為內容。But on a particular control instance you might want to change its value versus the common templated value, such as giving that control a different background color or a different text string as content. Windows 執行階段屬性系統會考量優先順序高於樣式與範本所提供值的本機值。The Windows Runtime property system considers local values at higher precedence than values provided by styles and templates. 這樣便能啟用讓應用程式特定的值覆寫範本的案例,因此,控制項對於您在應用程式 UI 中自行使用它們而言非常有用。That enables the scenario of having app-specific values overwrite the templates so that the controls are useful for your own use of them in app UI.

相依性屬性優先順序清單Dependency property precedence list

下列是指派相依性屬性的執行階段值時,屬性系統使用的決定性順序。The following is the definitive order that the property system uses when assigning the run-time value for a dependency property. 最高優先順序會先列出。Highest precedence is listed first. 您只需瀏覽這個清單,就能找到更詳細的說明。You'll find more detailed explanations just past this list.

  1. 動畫值: 作用中動畫、視覺狀態動畫,或具有 HoldEnd 行為的動畫。Animated values: Active animations, visual state animations, or animations with a HoldEnd behavior. 為取得任何實際效果,套用到屬性的動畫優先順序必須高於基礎 (未動畫化的) 值,即使該值是在本機設定也一樣。To have any practical effect, an animation applied to a property must have precedence over the base (unanimated) value, even if that value was set locally.
  2. 本機值: 本機值可以輕鬆透過屬性包裝函式設定,這也等同於在 XAML 中設定為屬性 (Attribute) 或屬性 (Property) 元素,或使用特定執行個體的屬性 (Property) 呼叫 SetValue 方法。Local value: A local value might be set through the convenience of the property wrapper, which also equates to setting as an attribute or property element in XAML, or by a call to the SetValue method using a property of a specific instance. 如果您使用繫結或靜態資源設定本機值,在優先順序上就像分別設定了本機值,如果設定了新的本機值,就會清除繫結或資源參考。If you set a local value by using a binding or a static resource, these each act in the precedence as if a local value was set, and bindings or resource references are erased if a new local value is set.
  3. 範本化屬性: 如果將元素建立為範本 (來自 ControlTemplateDataTemplate) 的一部分,元素就會含有這些屬性。Templated properties: An element has these if it was created as part of a template (from a ControlTemplate or DataTemplate).
  4. Style Setter: 頁面或應用程式資源樣式中的 Setter 值。Style setters: Values from a Setter within styles from page or application resources.
  5. 預設值: 相依性屬性可以有預設值做為其中繼資料的一部分。Default value: A dependency property can have a default value as part of its metadata.

範本化屬性Templated properties

做為優先順序項目的範本化屬性不會套用到您直接在 XAML 頁面標記中宣告的任何元素屬性。Templated properties as a precedence item do not apply to any property of an element that you declare directly in XAML page markup. 範本化屬性概念只存在 Windows 執行階段將 XAML 範本套用到 UI 元素,從而定義其視覺效果時建立的物件中。The templated property concept exists only for objects that are created when the Windows Runtime applies a XAML template to a UI element and thus defines its visuals.

從控制項範本設定的所有屬性都含有某些種類的值。All the properties that are set from a control template have values of some kind. 這些值一般都與一組控制項延伸的預設值類似,而且通常與您稍後可藉由直接設定屬性值的方式重設的值產生關聯。These values are almost like an extended set of default values for the control and are often associated with values you can reset later by setting the property values directly. 因此,由範本設定的值必須能夠和實際的本機值區分,如此一來,任何新的本機值便能覆寫它。Thus the template-set values must be distinguishable from a true local value, so that any new local value can overwrite it.

注意

在某些情況下,如果範本無法為應可在執行個體上設定的屬性公開 {TemplateBinding} 標記延伸參考,範本甚至可能覆寫本機值。In some cases the template might override even local values, if the template failed to expose {TemplateBinding} markup extension references for properties that should have been settable on instances. 這通常只有在屬性確實不是要在執行個體上設定時才會完成,例如,如果它只與視覺效果和範本行為相關,但與使用範本之控制項所需的函式或執行階段邏輯無關。This is usually done only if the property is really not intended to be set on instances, for example if it's only relevant to visuals and template behavior and not to the intended function or runtime logic of the control that uses the template.

繫結與優先順序Bindings and precedence

繫結操作針對將它們用於任何範圍的情況都具有適當的優先順序。Binding operations have the appropriate precedence for whatever scope they're used for. 例如,套用到本機值的 {Binding} 會以本機值的方式運作,而屬性 setter 的 {TemplateBinding} 標記延伸的套用方式與樣式 setter 一樣。For example, a {Binding} applied to a local value acts as local value, and a {TemplateBinding} markup extension for a property setter applies as a style setter does. 由於繫結必須等到執行階段從資料來源取得值,因此,判斷任何屬性的屬性值優先順序的程序也會延伸到執行階段。Because bindings must wait until run-time to obtain values from data sources, the process of determining the property value precedence for any property extends into run-time as well.

繫結不只和本機值具有相同優先順序,它們實際上也是本機值,其中繫結是已延遲之值的預留位置。Not only do bindings operate at the same precedence as a local value, they really are a local value, where the binding is the placeholder for a value that is deferred. 如果您的屬性值含有繫結,且您在執行階段於其上設定了本機值,則它會完全取代繫結。If you have a binding in place for a property value, and you set a local value on it at run-time, that replaces the binding entirely. 同理,如果您呼叫 SetBinding 來定義只存在執行階段的繫結,則您可以取代任何已在 XAML 中套用的本機值,或者使用先前執行的程式碼來取代。Similarly, if you call SetBinding to define a binding that only comes into existence at run-time, you replace any local value you might have applied in XAML or with previously executed code.

腳本動畫和基礎值Storyboarded animations and base value

腳本動畫是以「基礎值」** 的概念來操作。Storyboarded animations act on a concept of a base value. 基礎值是屬性系統使用它的優先順序來判斷的值,但會省略尋找動畫的最後一個步驟。The base value is the value that's determined by the property system using its precedence, but omitting that last step of looking for animations. 例如,基礎值可能來自控制項的範本,也可能來自在控制項執行個體上設定本機值。For example, a base value might come from a control's template, or it might come from setting a local value on an instance of a control. 無論使用何種方法,只要您的動畫持續執行,套用動畫將覆寫這個基礎值並套用動畫值。Either way, applying an animation will overwrite this base value and apply the animated value for as long as your animation continues to run.

對於動畫屬性,如果該動畫未明確指定 FromTo,或者,如果動畫會在完成時將屬性還原為其基礎值,基礎值就仍能對動畫值產生影響。For an animated property, the base value can still have an effect on the animation's behavior, if that animation does not explicitly specify both From and To, or if the animation reverts the property to its base value when completed. 在這些情況下,當動畫不再執行之後,就會再次使用剩餘的優先順序。In these cases, once an animation is no longer running, the rest of the precedence is used again.

但是,以 HoldEnd 行為指定 To 的動畫在移除之前可以覆寫本機值,即使它看起來像是已停止也一樣。However, an animation that specifies a To with a HoldEnd behavior can override a local value until the animation is removed, even when it visually appears to be stopped. 概念上來說,這就像是一個會永久執行的動畫,即使 UI 中不含視覺動畫也一樣。Conceptually this is like an animation that's running forever even if there is not a visual animation in the UI.

多重動畫可套用到單一屬性。Multiple animations can be applied to a single property. 這其中每一個動畫可能都已定義來取代來自值優先順序中不同時點的基礎值。Each of these animations might have been defined to replace base values that came from different points in the value precedence. 但是,這些動畫都將在執行階段同時執行,這通常表示它們必須結合其值,因為每一個動畫對於值的影響都一樣。However, these animations will all be running simultaneously at run time, and that often means that they must combine their values because each animation has equal influence on the value. 這完全取決於動畫的定義方式,以及要顯示為動畫之值的類型。This depends on exactly how the animations are defined, and the type of the value that is being animated.

如需詳細資訊,請參閱腳本動畫For more info, see Storyboarded animations.

預設值Default values

如需更多使用 PropertyMetadata 值建立相依性屬性預設值的詳細資料,請參閱自訂相依性屬性主題。Establishing the default value for a dependency property with a PropertyMetadata value is explained in more detail in the Custom dependency properties topic.

即使未在相依性屬性的中繼資料中明確定義這些預設值,該屬性仍會有預設值。Dependency properties still have default values even if those default values weren't explicitly defined in that property's metadata. 除非已使用中繼資料變更它們,否則 Windows 執行階段相依性屬性的預設值通常是下列其中一項:Unless they have been changed by metadata, default values for the Windows Runtime dependency properties are generally one of the following:

  • 使用執行階段物件或基本 Object 類型 (「參考類型」**) 的屬性具有 null 的預設值。A property that uses a run-time object or the basic Object type (a reference type) has a default value of null. 例如,在刻意設定或繼承 DataContext 之前,它會是 nullFor example, DataContext is null until it's deliberately set or is inherited.
  • 使用像是數值或布林值 (「值類型」**) 等基礎值的屬性,會使用該值的預期預設值。A property that uses a basic value such as numbers or a Boolean value (a value type) uses an expected default for that value. 例如,若為整數和浮點數則為 0,若為布林值則為 falseFor example, 0 for integers and floating-point numbers, false for a Boolean.
  • 使用 Windows 執行階段結構的屬性預設值,可透過呼叫該結構的隱含預設建構函式來取得。A property that uses a Windows Runtime structure has a default value that's obtained by calling that structure's implicit default constructor. 這個建構函式會針對結構的每一個基礎值欄位使用預設值。This constructor uses the defaults for each of the basic value fields of the structure. 例如,Point 值的預設值會使用它的 XY 值初始化為 0。For example, a default for a Point value is initialized with its X and Y values as 0.
  • 使用列舉的屬性預設值為該列舉中第一個定義的成員。A property that uses an enumeration has a default value of the first defined member in that enumeration. 檢查特定列舉的參考,以查看預設值為何。Check the reference for specific enumerations to see what the default value is.
  • 使用字串 (適用於 .NET 的 System.String、適用於 C++/CX 的 Platform::String) 的屬性預設值為空字串 ("")。A property that uses a string (System.String for .NET, Platform::String for C++/CX) has a default value of an empty string ("").
  • 根據本主題中深入探討的因素,集合屬性通常不會實作為相依性屬性。Collection properties aren't typically implemented as dependency properties, for reasons discussed further on in this topic. 但是,如果您實作自訂集合屬性且想要讓它成為相依性屬性,請確定會避免「不想要的單一執行個體」**,如接近自訂相依性屬性結尾處所述。But if you implement a custom collection property and you want it to be a dependency property, make sure to avoid an unintentional singleton as described near the end of Custom dependency properties.

相依性屬性提供的屬性功能Property functionality provided by a dependency property

資料繫結Data binding

相依性屬性可以透過套用資料繫結來設定它的值。A dependency property can have its value set through applying a data binding. 資料繫結在 XAML 中使用 {Binding} 標記延伸語法,在程式碼中使用 {x:Bind} 標記延伸Binding 類別。Data binding uses the {Binding} markup extension syntax in XAML, {x:Bind} markup extension or the Binding class in code. 針對資料繫結屬性,最終的屬性值判斷會延遲到執行階段。For a databound property, the final property value determination is deferred until run time. 那時就會從資料來源中取得該值。At that time the value is obtained from a data source. 相依性屬性系統在此處扮演的角色是,讓預留位置行為能夠運作,例如,在尚未知道值時載入 XAML,然後透過與 Windows 執行階段資料繫結引擎互動,在執行階段提供值。The role that the dependency property system plays here is enabling a placeholder behavior for operations like loading XAML when the value is not yet known, and then supplying the value at run time by interacting with the Windows Runtime data binding engine.

下列範例會在 XAML 中使用繫結,以設定 TextBlock 元素的 Text 值。The following example sets the Text value for a TextBlock element, using a binding in XAML. 繫結會使用繼承的資料內容與物件資料來源The binding uses an inherited data context and an object data source. (這個簡短範例中並未顯示這兩者,如需顯示內容與來源的更完整範例,請參閱深入了解資料繫結)。(Neither of these is shown in the shortened example; for a more complete sample that shows context and source, see Data binding in depth.)

<Canvas>
  <TextBlock Text="{Binding Team.TeamName}"/>
</Canvas>

您也可以使用程式碼建立繫結,而不要使用 XAML。You can also establish bindings using code rather than XAML. 請參閱 SetBindingSee SetBinding.

注意

這類系結會被視為相依性屬性值優先順序用途的區域值。Bindings like this are treated as a local value for purposes of dependency property value precedence. 如果您將另一個本機值設成原先擁有 Binding 值的屬性,將會完全覆寫該繫結,而不只是繫結的執行階段值。If you set another local value for a property that originally held a Binding value, you will overwrite the binding entirely, not just the binding's run-time value. {x:Bind} 繫結會使用產生的程式碼 (將會為屬性設定本機值) 來實作。{x:Bind} Bindings are implemented using generated code that will set a local value for the property. 如果您針對使用 {x:Bind} 的屬性設定了本機值,那麼下一次評估繫結時 (例如當繫結在其來源物件上觀察到屬性變更時) 將會取代該值。If you set a local value for a property that is using {x:Bind}, then that value will be replaced the next time the binding is evaluated, such as when it observes a property change on its source object.

繫結來源、繫結目標、FrameworkElement 的角色Binding sources, binding targets, the role of FrameworkElement

若要做為繫結來源,屬性不需是相依性屬性;儘管這會根據您的程式設計語言而定且每個都擁有特定的邊緣案例,但是您通常可以使用任一屬性做為繫結來源。To be the source of a binding, a property does not need to be a dependency property; you can generally use any property as a binding source, although this depends on your programming language and each has certain edge cases. 不過,要成為 {Binding} 標記延伸Binding 的目標,該屬性必須是相依性屬性。However, to be the target of a {Binding} markup extension or Binding, that property must be a dependency property. {x:Bind} 不需要這項需求,因為它是使用產生的程式碼來套用它的繫結值。{x:Bind} does not have this requirement as it uses generated code to apply its binding values.

如果您正在程式碼中建立繫結,請注意,SetBinding API 只針對 FrameworkElement 進行定義。If you are creating a binding in code, note that the SetBinding API is defined only for FrameworkElement. 不過,您可以改用 BindingOperations 來建立繫結定義,以參考任何 DependencyObject 屬性。However, you can create a binding definition using BindingOperations instead, and thus reference any DependencyObject property.

無論是使用程式碼或 XAML,請記住 DataContextFrameworkElement 屬性。For either code or XAML, remember that DataContext is a FrameworkElement property. 透過使用父系-子系屬性繼承格式 (通常建立在 XAML 標記中),繫結系統可以解析存在父元素中的 DataContextBy using a form of parent-child property inheritance (typically established in XAML markup), the binding system can resolve a DataContext that exists on a parent element. 即使子物件 (擁有目標屬性) 不是 FrameworkElement,這個繼承仍然可以評估,因此不會包含它自己的 DataContext 值。This inheritance can evaluate even if the child object (which has the target property) is not a FrameworkElement and therefore does not hold its own DataContext value. 不過,要繼承的父元素必須是 FrameworkElement,才能設定與包含 DataContextHowever, the parent element being inherited must be a FrameworkElement in order to set and hold the DataContext. 或者,您必須定義繫結,繫結才能以 null 值的 DataContext 作用。Alternatively, you must define the binding such that it can function with a null value for DataContext.

建立繫結不是大多數資料繫結案例唯一需要做的事。Wiring the binding is not the only thing that's needed for most data binding scenarios. 如果要讓單向或雙向繫結生效,來源屬性必須支援傳播到繫結系統 (因此就是目標) 的來源屬性。For a one-way or two-way binding to be effective, the source property must support change notifications that propagate to the binding system and thus the target. 針對自訂的繫結來源,這表示屬性必須是相依性屬性,或物件必須支援 INotifyPropertyChangedFor custom binding sources, this means that the property must be a dependency property, or the object must support INotifyPropertyChanged. 集合應支援 INotifyCollectionChangedCollections should support INotifyCollectionChanged. 某些類別在它們的實作中支援這些介面,因此使用它們做為基底類別對資料繫結案例來說很有用;ObservableCollection<T> 是這種類別的範例之一。Certain classes support these interfaces in their implementations so that they are useful as base classes for data binding scenarios; an example of such a class is ObservableCollection<T>. 如需有關資料繫結以及資料繫結如何與屬性系統建立關聯的詳細資訊,請參閱深入了解資料繫結For more information on data binding and how data binding relates to the property system, see Data binding in depth.

注意

此處所列的類型支援 Microsoft .NET 資料來源。The types listed here support Microsoft .NET data sources. C++/CX 資料來源會針對變更通知或可觀察的行為使用不同的介面,請參閱深入了解資料繫結C++/CX data sources use different interfaces for change notification or observable behavior, see Data binding in depth.

樣式及範本Styles and templates

樣式與範本是將屬性定義為相依性屬性的其中兩個案例。Styles and templates are two of the scenarios for properties being defined as dependency properties. 樣式對於定義應用程式 UI 的屬性設定相當有用。Styles are useful for setting properties that define the app's UI. 樣式在 XAML 中會定義為資源,是定義為 Resources 集合中的項目,或是定義在個別的 XAML 檔案 (例如佈景主題資源字典) 中。Styles are defined as resources in XAML, either as an entry in a Resources collection, or in separate XAML files such as theme resource dictionaries. 樣式會與屬性系統互動,因為它們包含屬性的 setter。Styles interact with the property system because they contain setters for properties. 這裡最重要的屬性就是 ControlControl.Template 屬性:它定義了 Control 的大部分視覺化外觀和視覺狀態。The most important property here is the Control.Template property of a Control: it defines most of the visual appearance and visual state for a Control. 如需樣式的詳細資訊,以及定義 Style 和使用 setter 的一些 XAML 範例,請參閱設定控制項的樣式For more info on styles, and some example XAML that defines a Style and uses setters, see Styling controls.

來自樣式或範本的值是延遲的值,與繫結類似。Values that come from styles or templates are deferred values, similar to bindings. 這是為了讓控制項使用者可以重新範本化控制項或重新定義樣式。This is so that control users can re-template controls or redefine styles. 此外,這就是為什麼樣式中的屬性只能以相依性屬性來操作,而不能以一般屬性來操作。And that's why property setters in styles can only act on dependency properties, not ordinary properties.

腳本動畫Storyboarded animations

您可以使用腳本動畫將相依性屬性的值製作成動畫。You can animate a dependency property's value using a storyboarded animation. Windows 執行階段中的腳本動畫不僅僅是視覺裝飾。Storyboarded animations in the Windows Runtime are not merely visual decorations. 這在考慮將動畫做為狀態機器技術時更有用,這類技術可設定個別屬性的值或所有屬性的值以及控制項的視覺效果,並且在一段時間後變更這些值。It's more useful to think of animations as being a state machine technique that can set the values of individual properties or of all properties and visuals of a control, and change these values over time.

若要動畫化,動畫的目標屬性必須是相依性屬性。To be animated, the animation's target property must be a dependency property. 此外,若要動畫化,現有的 Timeline 衍生動畫類型之一必須支援目標屬性的值類型。Also, to be animated, the target property's value type must be supported by one of the existing Timeline-derived animation types. ColorDoublePoint 的值可以使用內插補點或主要畫面格技術來製作動畫效果。Values of Color, Double and Point can be animated using either interpolation or keyframe techniques. 大部分的其他值可以使用分離的 Object 主要畫面格來製作動畫效果。Most other values can be animated using discrete Object key frames.

套用與執行動畫時,動畫化的值的優先順序高於屬性另外包含的任何值 (像是本機值)。When an animation is applied and running, the animated value operates at a higher precedence than any value (such as a local value) that the property otherwise has. 動畫也包含一個選擇性的 HoldEnd 行為,即使動畫看起來像是已停止,仍會造成動畫套用到屬性值。Animations also have an optional HoldEnd behavior that can cause animations to apply to property values even if the animation visually appears to be stopped.

狀態電腦原則的具體表現方式是使用腳本動畫做為控制項的 VisualStateManager 狀態模型的一部分。The state machine principle is embodied by the use of storyboarded animations as part of the VisualStateManager state model for controls. 如需腳本動畫的詳細資訊,請參閱腳本動畫For more info on storyboarded animations, see Storyboarded animations. 如需 VisualStateManager 和定義控制項視覺狀態的詳細資訊,請參閱視覺狀態的腳本動畫控制項範本For more info on VisualStateManager and defining visual states for controls, see Storyboarded animations for visual states or Control templates.

屬性變更的行為Property-changed behavior

屬性變更的行為是相依性屬性詞彙「相依性」部分的根源。Property-changed behavior is the origin of the "dependency" part of dependency property terminology. 在許多架構中,當另一個屬性會影響第一個屬性的值時,要維持某個屬性的有效值是很棘手的開發問題。Maintaining valid values for a property when another property can influence the first property's value is a difficult development problem in many frameworks. 在 Windows 執行階段屬性系統中,每個相依性屬性都可以指定一個回呼,該回呼會在它的屬性值變更時叫用。In the Windows Runtime property system, each dependency property can specify a callback that is invoked whenever its property value changes. 使用這個回呼通常可以同時通知或變更相關屬性值。This callback can be used to notify or change related property values, in a generally synchronous manner. 許多現有的相依性屬性都包含一個屬性變更的行為。Many existing dependency properties have a property-changed behavior. 您也可以新增類似的回呼行為到自訂相依性屬性,並實作您自己的屬性變更行為。You can also add similar callback behavior to custom dependency properties, and implement your own property-changed callbacks. 請參閱自訂相依性屬性中的範例。See Custom dependency properties for an example.

Windows 10 引進了 RegisterPropertyChangedCallback 方法。Windows 10 introduces the RegisterPropertyChangedCallback method. 這可讓應用程式程式碼在 DependencyObject 執行個體上的指定相依性屬性變更時登錄變更通知。This enables application code to register for change notifications when the specified dependency property is changed on an instance of DependencyObject.

預設值與 ClearValueDefault value and ClearValue

相依性屬性可以在其屬性中繼資料中定義一個預設值。A dependency property can have a default value defined as part of its property metadata. 針對相依性屬性,它的預設值不會在第一次設定屬性預設值之後變成無關的。For a dependency property, its default value doesn't become irrelevant after the property's been set the first time. 每當值優先順序中有一些其他行列式消失時,預設值可能會在執行階段再次套用。The default value might apply again at run-time whenever some other determinant in value precedence disappears. (相依性屬性值的優先順序會在下一節中討論)。例如,您可能會刻意移除套用到屬性的樣式值或動畫,但卻希望這樣做之後,將該值設定為合理的預設值。(Dependency property value precedence is discussed in the next section.) For example, you might deliberately remove a style value or an animation that applies to a property, but you want the value to be a reasonable default after you do so. 相依性屬性的預設值可以提供這個值,而不需要執行額外步驟來特別設定每個屬性的值。The dependency property default value can provide this value, without needing to specifically set each property's value as an extra step.

即使在您已經使用本機值來設定屬性之後,您還是能夠刻意將該屬性設為預設值。You can deliberately set a property to the default value even after you have already set it with a local value. 若要再次將值重設為預設值,並且還要一併啟用可能覆寫預設值但不會覆寫本機值的優先順序中的其他參與者,可以呼叫 ClearValue 方法 (參考要清除的屬性以做為方法參數)。To reset a value to be the default again, and also to enable other participants in precedence that might override the default but not a local value, call the ClearValue method (reference the property to clear as a method parameter). 您不一定想讓屬性照字面使用預設值,但是清除本機值並還原為預設值,可能會讓優先順序中您所需的另一個項目立即運作,例如,使用來自控制項範本中樣式 setter 的值。You don't always want the property to literally use the default value, but clearing the local value and reverting to the default value might enable another item in precedence that you want to act now, such as using the value that came from a style setter in a control template.

DependencyObject 和執行緒DependencyObject and threading

所有的 DependencyObject 執行個體都必須在 UI 執行緒上建立,而這個執行緒與 Windows 執行階段 app 所顯示的目前 Window 關聯。All DependencyObject instances must be created on the UI thread which is associated with the current Window that is shown by a Windows Runtime app. 雖然每個 DependencyObject 都必須在主 UI 執行緒上建立,但是只要存取 Dispatcher 屬性,即可使用其他緒行緒的發送器參考來存取物件。Although each DependencyObject must be created on the main UI thread, the objects can be accessed using a dispatcher reference from other threads, by accessing the Dispatcher property. 接著,您可以在 CoreDispatcher 物件上呼叫像是 RunAsync 的方法,並在 UI 執行緒上的執行緒限制規則內執行您的程式碼。Then you can call methods such as RunAsync on the CoreDispatcher object, and execute your code within the rules of thread restrictions on the UI thread.

DependencyObject 的執行緒層面都是相關的,因為它通常表示只有在 UI 執行緒上執行的程式碼才可以變更或甚至是讀取相依性屬性的值。The threading aspects of DependencyObject are relevant because it generally means that only code that runs on the UI thread can change or even read the value of a dependency property. 在一般的 UI 程式碼中通常可以避免緒行緒處理的問題,因為它能夠正確使用 async 模式及背景工作者執行緒。Threading issues can usually be avoided in typical UI code that makes correct use of async patterns and background worker threads. 通常您只會在定義自己的 DependencyObject 類型並且嘗試在 DependencyObject 不適用的資料來源或其他案例中使用這些類型時,才會遇到 DependencyObject 相關的執行緒處理問題。You typically only run into DependencyObject-related threading issues if you are defining your own DependencyObject types and you attempt to use them for data sources or other scenarios where a DependencyObject isn't necessarily appropriate.

概念資料Conceptual material