XAML 語法詳細資料XAML Syntax In Detail

本主題定義用來描述 XAML 語法元素的詞彙。This topic defines the terms that are used to describe the elements of XAML syntax. 本檔的其餘部分會經常使用這些詞彙,這兩者都是針對 WPF 檔,特別是針對使用 XAML 的其他架構,或是在 .xaml 層級由 XAML 語言支援啟用的基本 XAML 概念。These terms are used frequently throughout the remainder of this documentation, both for WPF documentation specifically and for the other frameworks that use XAML or the basic XAML concepts enabled by the XAML language support at the System.Xaml level. 本主題將針對XAML 總覽(WPF)主題中引進的基本術語進行擴充。This topic expands on the basic terminology introduced in the topic XAML Overview (WPF).

XAML 語言規格The XAML Language Specification

在此定義的 XAML 語法詞彙也會在 XAML 語言規格中定義或參考。The XAML syntax terminology defined here is also defined or referenced within the XAML language specification. XAML 是以 XML 為基礎的語言,並在 XML 結構化規則之後遵循或擴充。XAML is a language based on XML and follows or expands upon XML structural rules. 有些術語是從共用,或是以描述 XML 語言或 XML 檔物件模型時常用的術語為基礎。Some of the terminology is shared from or is based on the terminology commonly used when describing the XML language or the XML document object model.

如需 XAML 語言規格的詳細資訊,請從 Microsoft 下載中心下載[MS-XAML]For more information about the XAML language specification, download [MS-XAML] from the Microsoft Download Center.

XAML 和 CLRXAML and CLR

XAML 是一種標記語言。XAML is a markup language. Common language runtime (CLR)(如其名稱所隱含)可啟用執行時間執行。The common language runtime (CLR), as implied by its name, enables runtime execution. XAML 本身不是 CLR 執行時間直接取用的其中一個通用語言。XAML is not by itself one of the common languages that is directly consumed by the CLR runtime. 取而代之的是,您可以將 XAML 視為支援它自己的型別系統。Instead, you can think of XAML as supporting its own type system. WPF 使用的特定 XAML 剖析系統建基於 CLR 和 CLR 型別系統。The particular XAML parsing system that is used by WPF is built on the CLR and the CLR type system. XAML 類型會對應至 CLR 類型,以在剖析 WPF 的 XAML 時具現化運行時程表示。XAML types are mapped to CLR types to instantiate a run time representation when the XAML for WPF is parsed. 基於這個理由,本檔中語法討論的其餘部分將包含 CLR 型別系統的參考,即使 XAML 語言規格中的對等語法討論不是如此。For this reason, the remainder of discussion of syntax in this document will include references to the CLR type system, even though the equivalent syntax discussions in the XAML language specification do not. (根據 XAML 語言規格層級,XAML 類型可以對應到任何其他類型系統,這不一定是 CLR,但這需要建立和使用不同的 XAML 剖析器)。(Per the XAML language specification level, XAML types could be mapped to any other type system, which does not have to be the CLR, but that would require the creation and use of a different XAML parser.)

類型和類別繼承的成員Members of Types and Class Inheritance

當做 WPFWPF 類型的 XAML 成員出現的屬性和事件,通常會繼承自基底類型。Properties and events as they appear as XAML members of a WPFWPF type are often inherited from base types. 例如,請考慮下列範例: <Button Background="Blue" .../>For example, consider this example: <Button Background="Blue" .../>. 如果您要查看類別定義、反映結果或檔,Background 屬性不是 Button 類別上立即宣告的屬性。The Background property is not an immediately declared property on the Button class, if you were to look at the class definition, reflection results, or the documentation. 而是繼承自基底 Control 類別的 BackgroundInstead, Background is inherited from the base Control class.

WPFWPF XAML 專案的類別繼承行為,是從 XML 標記的架構強制轉譯中很重要的。The class inheritance behavior of WPFWPF XAML elements is a significant departure from a schema-enforced interpretation of XML markup. 類別繼承可能會變得複雜,特別是當中繼基類是抽象的,或涉及介面時。Class inheritance can become complex, particularly when intermediate base classes are abstract, or when interfaces are involved. 這是一項原因,那就是 XAML 元素的集合及其允許的屬性,很難正確地表示,並使用一般用於 XML 程式設計的架構類型,例如 DTD 或 XSD 格式。This is one reason that the set of XAML elements and their permissible attributes is difficult to represent accurately and completely using the schema types that are typically used for XML programming, such as DTD or XSD format. 另一個原因是 XAML 語言本身的擴充性和類型對應功能,會排除所允許之類型和成員的任何固定標記法的完整性。Another reason is that extensibility and type-mapping features of the XAML language itself preclude completeness of any fixed representation of the permissible types and members.

物件元素語法Object Element Syntax

物件元素語法是 XAML 標記語法,會藉由宣告 XML 專案來具現化 CLR 類別或結構。Object element syntax is the XAML markup syntax that instantiates a CLR class or structure by declaring an XML element. 此語法類似其他標記語言(例如 HTML)的元素語法。This syntax resembles the element syntax of other markup languages such as HTML. 物件元素語法以左角括弧(<)開頭,後面緊接著要具現化之類別或結構的類型名稱。Object element syntax begins with a left angle bracket (<), followed immediately by the type name of the class or structure being instantiated. 零或多個空格可以遵循類型名稱,而且也可以在 object 元素上宣告零個或多個屬性,並以一或多個空格分隔每個屬性名稱 = "value" 配對。Zero or more spaces can follow the type name, and zero or more attributes may also be declared on the object element, with one or more spaces separating each attribute name="value" pair. 最後,必須符合下列其中一項條件:Finally, one of the following must be true:

  • 元素和標記必須以正斜線(/)關閉,後面緊接著右角括弧(>)。The element and tag must be closed by a forward slash (/) followed immediately by a right angle bracket (>).

  • 開頭標記必須以右角括弧(>)完成。The opening tag must be completed by a right angle bracket (>). 其他物件元素、屬性專案或內部文字則可以跟隨在開頭標記之後。Other object elements, property elements, or inner text, can follow the opening tag. 此處所包含的內容,通常會受到元素的物件模型所限制。Exactly what content may be contained here is typically constrained by the object model of the element. 物件元素的對等結束記號也必須存在,以適當的對應,並與其他開頭和結束記號配對進行平衡。The equivalent closing tag for the object element must also exist, in proper nesting and balance with other opening and closing tag pairs.

.NET 所實作為的 XAML 具有一組規則,可將物件元素對應至類型、屬性為屬性或事件,以及 XAML 命名空間與 CLR 命名空間加上元件。XAML as implemented by .NET has a set of rules that map object elements into types, attributes into properties or events, and XAML namespaces to CLR namespaces plus assembly. 針對 WPF 和 .NET,XAML 物件專案會對應至所參考元件中所定義的 .NET 類型,而屬性會對應至這些類型的成員。For WPF and .NET, XAML object elements map to .NET types as defined in referenced assemblies, and the attributes map to members of those types. 當您在 XAML 中參考 CLR 型別時,您也可以存取該型別的繼承成員。When you reference a CLR type in XAML, you have access to the inherited members of that type as well.

例如,下列範例是將 Button 類別的新實例具現化的物件專案語法,同時也會指定 Name 屬性和該屬性的值:For example, the following example is object element syntax that instantiates a new instance of the Button class, and also specifies a Name attribute and a value for that attribute:

<Button Name="CheckoutButton"/>

下列範例是物件元素語法,其中也包含 XAML 內容屬性語法。The following example is object element syntax that also includes XAML content property syntax. 包含在內的內部文字將用來設定 TextBox XAML 內容屬性 TextThe inner text contained within will be used to set the TextBox XAML content property, Text.

<TextBox>This is a Text Box</TextBox>

內容模型Content Models

在語法方面,類別可能支援使用當做 XAML 物件專案,但當應用程式或頁面放在整體內容模型或專案樹狀結構的預期位置時,該專案將只能在該元素中正常運作。A class might support a usage as a XAML object element in terms of the syntax, but that element will only function properly in an application or page when it is placed in an expected position of an overall content model or element tree. 例如,MenuItem 通常只能放在 MenuBase 衍生類別(例如 Menu)的子系。For example, a MenuItem should typically only be placed as a child of a MenuBase derived class such as Menu. 特定專案的內容模型會記載為控制項的類別頁面上的批註,以及可當做 XAML 專案使用的其他 WPFWPF 類別的一部分。Content models for specific elements are documented as part of the remarks on the class pages for controls and other WPFWPF classes that can be used as XAML elements.

物件元素的屬性Properties of Object Elements

XAML 中的屬性是由各種可能的語法所設定。Properties in XAML are set by a variety of possible syntaxes. 根據您所設定之屬性的基礎類型系統特性而定,特定屬性可以使用哪種語法會有所不同。Which syntax can be used for a particular property will vary, based on the underlying type system characteristics of the property that you are setting.

藉由設定屬性的值,您可以將功能或特性加入至物件,因為它們存在於執行時間物件圖形中。By setting values of properties, you add features or characteristics to objects as they exist in the run time object graph. 從物件元素建立之物件的初始狀態是以無參數的函式行為為基礎。The initial state of the created object from a object element is based on the parameterless constructor behavior. 一般來說,您的應用程式會使用任何指定物件的完全預設實例以外的專案。Typically, your application will use something other than a completely default instance of any given object.

屬性 (Attribute) 語法 (屬性(Property))Attribute Syntax (Properties)

屬性語法是 XAML 標記語法,會藉由宣告現有物件專案上的屬性來設定屬性的值。Attribute syntax is the XAML markup syntax that sets a value for a property by declaring an attribute on an existing object element. 屬性名稱必須符合可支援相關物件專案之類別的屬性(property)的 CLR 成員名稱。The attribute name must match the CLR member name of the property of the class that backs the relevant object element. 屬性名稱後面接著指派運算子(=)。The attribute name is followed by an assignment operator (=). 屬性值必須是括在引號內的字串。The attribute value must be a string enclosed within quotes.

注意

您可以使用替代引號將常值引號放在屬性中。You can use alternating quotes to place a literal quotation mark within an attribute. 例如,您可以使用單引號來宣告字串,其中包含其中的雙引號字元。For instance you can use single quotes as a means to declare a string that contains a double quote character within it. 無論您使用單引號或雙引號,都應該使用相符的配對來開啟和關閉屬性值字串。Whether you use single or double quotes, you should use a matching pair for opening and closing the attribute value string. 還有其他可用來處理任何特定 XAML 語法所加上之字元限制的逸出序列或其他技術。There are also escape sequences or other techniques available for working around character restrictions imposed by any particular XAML syntax. 請參閱XML 字元實體和 XAMLSee XML Character Entities and XAML.

若要透過屬性語法設定,屬性必須是公用的,而且必須是可寫入的。In order to be set through attribute syntax, a property must be public and must be writeable. 支援型別系統中的屬性值必須是實值型別,或必須是參考型別,而且在存取相關的支援型別時,XAML 處理器可以加以具現化或參照。The value of the property in the backing type system must be a value type, or must be a reference type that can be instantiated or referenced by a XAML processor when accessing the relevant backing type.

針對 WPF XAML 事件,當做屬性名稱參考的事件必須是公用的,而且具有公用委派。For WPF XAML events, the event that is referenced as the attribute name must be public and have a public delegate.

屬性或事件必須是包含物件元素所具現化之類別或結構的成員。The property or event must be a member of the class or structure that is instantiated by the containing object element.

屬性值的處理Processing of Attribute Values

開頭和結尾引號中包含的字串值是由 XAML 處理器處理。The string value contained within the opening and closing quotation marks is processed by a XAML processor. 對於屬性,預設的處理行為取決於基礎 CLR 屬性的類型。For properties, the default processing behavior is determined by the type of the underlying CLR property.

屬性值是以下列其中一種方式填入,使用此處理順序:The attribute value is filled by one of the following, using this processing order:

  1. 如果 XAML 處理器遇到大括弧,或衍生自 MarkupExtension的 object 專案,則會先評估參考的標記延伸,而不是將值當做字串來處理,而標記延伸所傳回的物件會當做值使用。If the XAML processor encounters a curly brace, or an object element that derives from MarkupExtension, then the referenced markup extension is evaluated first rather than processing the value as a string, and the object returned by the markup extension is used as the value. 在許多情況下,標記延伸所傳回的物件將會是現有物件的參考,或是延遲評估到執行時間的運算式,而且不是新具現化的物件。In many cases the object returned by a markup extension will be a reference to an existing object, or an expression that defers evaluation until run time, and is not a newly instantiated object.

  2. 如果屬性是以屬性化 TypeConverter宣告,或該屬性的實值型別是以屬性化 TypeConverter宣告,則會將屬性的字串值提交至類型轉換器做為轉換輸入,而轉換器會傳回新的物件。示例.If the property is declared with an attributed TypeConverter, or the value type of that property is declared with an attributed TypeConverter, the string value of the attribute is submitted to the type converter as a conversion input, and the converter will return a new object instance.

  3. 如果沒有 TypeConverter,會嘗試直接轉換為屬性類型。If there is no TypeConverter, a direct conversion to the property type is attempted. 這個最終層級是 XAML 語言基本型別之間的剖析器原生值直接轉換,或在列舉中檢查已命名常數的名稱(剖析器接著會存取相符的值)。This final level is a direct conversion at the parser-native value between XAML language primitive types, or a check for the names of named constants in an enumeration (the parser then accesses the matching values).

列舉屬性值Enumeration Attribute Values

Xaml 中的列舉是由 XAML 剖析器在本質上進行處理,而且您應該指定其中一個列舉的已命名常數的字串名稱,來指定列舉的成員。Enumerations in XAML are processed intrinsically by XAML parsers, and the members of an enumeration should be specified by specifying the string name of one of the enumeration's named constants.

針對 nonflag 列舉值,原生行為是處理屬性值的字串,並將其解析為其中一個列舉值。For nonflag enumeration values, the native behavior is to process the string of an attribute value and resolve it to one of the enumeration values. 您未在格式列舉中指定列舉。,如同您在程式碼中所做的一樣。You do not specify the enumeration in the format Enumeration.Value, as you do in code. 相反地,您只指定,而列舉是由您所設定之屬性的型別推斷。Instead, you specify only Value, and Enumeration is inferred by the type of the property you are setting. 如果您在列舉中指定屬性,則為。形式,將無法正確解析。If you specify an attribute in the Enumeration.Value form, it will not resolve correctly.

針對旗標型列舉,行為是以 Enum.Parse 方法為基礎。For flagwise enumerations, the behavior is based on the Enum.Parse method. 您可以使用逗號分隔每個值,以指定旗標型列舉的多個值。You can specify multiple values for a flagwise enumeration by separating each value with a comma. 不過,您無法結合未旗標型的列舉值。However, you cannot combine enumeration values that are not flagwise. 比方說,您不能使用逗號語法來嘗試建立 Trigger,以作用於 nonflag 列舉的多個條件:For instance, you cannot use the comma syntax to attempt to create a Trigger that acts on multiple conditions of a nonflag enumeration:

<!--This will not compile, because Visibility is not a flagwise enumeration.-->  
...  
<Trigger Property="Visibility" Value="Collapsed,Hidden">  
  <Setter ... />  
</Trigger>  
...  

在 WPF 中,支援可在 XAML 中設定之屬性的旗標型列舉很罕見。Flagwise enumerations that support attributes that are settable in XAML are rare in WPF. 不過,其中一個列舉 StyleSimulationsHowever, one such enumeration is StyleSimulations. 例如,您可以使用逗號分隔的旗標型屬性語法來修改 Glyphs 類別的備註中提供的範例;StyleSimulations = "BoldSimulation" 可能會 StyleSimulations = "BoldSimulation,ItalicSimulation"You could, for instance, use the comma-delimited flagwise attribute syntax to modify the example provided in the Remarks for the Glyphs class; StyleSimulations = "BoldSimulation" could become StyleSimulations = "BoldSimulation,ItalicSimulation". KeyBinding.Modifiers 是可指定一個以上列舉值的另一個屬性。KeyBinding.Modifiers is another property where more than one enumeration value can be specified. 不過,這個屬性剛好是特殊案例,因為 ModifierKeys 列舉支援它自己的類型轉換器。However, this property happens to be a special case, because the ModifierKeys enumeration supports its own type converter. 修飾詞的類型轉換子會使用加號(+)做為分隔符號,而不是逗號(,)。The type converter for modifiers uses a plus sign (+) as a delimiter rather than a comma (,). 這項轉換支援更傳統的語法來表示 Microsoft Windows 程式設計中的主要組合,例如 "Ctrl + Alt"。This conversion supports the more traditional syntax to represent key combinations in Microsoft Windows programming, such as "Ctrl+Alt".

屬性和事件成員名稱參考Properties and Event Member Name References

當指定屬性時,您可以參考任何屬性或事件,該專案會以您為包含物件專案所具現化之 CLR 類型的成員形式存在。When specifying an attribute, you can reference any property or event that exists as a member of the CLR type you instantiated for the containing object element.

或者,您可以參考附加屬性或附加事件,而不受包含物件元素的影響。Or, you can reference an attached property or attached event, independent of the containing object element. (後續章節將討論附加的屬性)。(Attached properties are discussed in an upcoming section.)

您也可以使用typeName,從任何可透過預設命名空間存取的物件來命名任何事件。事件的部分限定名稱;此語法支援附加路由事件的處理常式,其中處理常式是用來處理從子專案路由的事件,但父項目在其 members 資料表中也不會有該事件。You can also name any event from any object that is accessible through the default namespace by using a typeName.event partially qualified name; this syntax supports attaching handlers for routed events where the handler is intended to handle events routing from child elements, but the parent element does not also have that event in its members table. 此語法類似附加事件語法,但此處的事件不是真正的附加事件。This syntax resembles an attached event syntax, but the event here is not a true attached event. 相反地,您會參考具有限定名稱的事件。Instead, you are referencing an event with a qualified name. 如需詳細資訊,請參閱路由事件總覽For more information, see Routed Events Overview.

在某些情況下,有時會提供屬性名稱做為屬性的值,而不是屬性名稱。For some scenarios, property names are sometimes provided as the value of an attribute, rather than the attribute name. 該屬性名稱也可以包含限定詞,例如以 [類型名稱 ] 格式指定的屬性。dependencyPropertyNameThat property name can also include qualifiers, such as the property specified in the form ownerType.dependencyPropertyName. 這種情況在 XAML 中撰寫樣式或範本時很常見。This scenario is common when writing styles or templates in XAML. 當做屬性值提供之屬性名稱的處理規則會不同,而且是由所設定的屬性類型或特定 WPF 子系統的行為所控制。The processing rules for property names provided as an attribute value are different, and are governed by the type of the property being set or by the behaviors of particular WPF subsystems. 如需詳細資訊,請參閱設定樣式和範本For details, see Styling and Templating.

屬性名稱的另一個用法是當屬性值描述屬性屬性關聯性時。Another usage for property names is when an attribute value describes a property-property relationship. 這項功能是用於資料系結和分鏡腳本目標,而且是由 PropertyPath 類別和其類型轉換器所啟用。This feature is used for data binding and for storyboard targets, and is enabled by the PropertyPath class and its type converter. 如需查閱語義的更完整描述,請參閱PROPERTYPATH XAML 語法For a more complete description of the lookup semantics, see PropertyPath XAML Syntax.

屬性元素語法Property Element Syntax

屬性專案語法是分歧的語法,與元素的基本 XML 語法規則有點類似。Property element syntax is a syntax that diverges somewhat from the basic XML syntax rules for elements. 在 XML 中,屬性的值是一種實際的字串,唯一可能的變化是使用的字串編碼格式。In XML, the value of an attribute is a de facto string, with the only possible variation being which string encoding format is being used. 在 XAML 中,您可以將其他物件元素指派為屬性的值。In XAML, you can assign other object elements to be the value of a property. 此功能是由屬性元素語法所啟用。This capability is enabled by the property element syntax. 屬性會使用elementTypeName中的開頭專案標記來指定,而不是指定為元素標記中的屬性。propertyName形式,屬性的值會在內指定,然後屬性專案就會關閉。Instead of the property being specified as an attribute within the element tag, the property is specified using an opening element tag in elementTypeName.propertyName form, the value of the property is specified within, and then the property element is closed.

具體而言,語法是以左角括弧(<)開頭,後面緊接著屬性元素語法所包含之類別或結構的類型名稱。Specifically, the syntax begins with a left angle bracket (<), followed immediately by the type name of the class or structure that the property element syntax is contained within. 後面緊接著單一點(.),然後依屬性的名稱,再接著右角括弧(>)。This is followed immediately by a single dot (.), then by the name of a property, then by a right angle bracket (>). 如同屬性語法,該屬性必須存在於所指定類型的宣告公用成員中。As with attribute syntax, that property must exist within the declared public members of the specified type. 要指派給屬性的值會包含在 property 元素中。The value to be assigned to the property is contained within the property element. 一般來說,此值會指定為一或多個物件專案,因為將物件指定為值,就是屬性專案語法的目的是要處理的案例。Typically, the value is given as one or more object elements, because specifying objects as values is the scenario that property element syntax is intended to address. 最後,指定相同elementTypeName的對等結束標記。必須提供propertyName組合,以適當的方式與其他專案標記進行嵌套和平衡。Finally, an equivalent closing tag specifying the same elementTypeName.propertyName combination must be provided, in proper nesting and balance with other element tags.

例如,下列是 ButtonContextMenu 屬性的屬性專案語法。For example, the following is property element syntax for the ContextMenu property of a Button.

<Button>
  <Button.ContextMenu>
    <ContextMenu>
      <MenuItem Header="1">First item</MenuItem>
      <MenuItem Header="2">Second item</MenuItem>
    </ContextMenu>
  </Button.ContextMenu>
  Right-click me!</Button>

如果指定的屬性型別是基本型別(例如 String)或指定名稱的列舉型別,則 property 專案中的值也可以指定為內部文字。The value within a property element can also be given as inner text, in cases where the property type being specified is a primitive value type, such as String, or an enumeration where a name is specified. 這兩種用法並不常見,因為每個案例也都可以使用較簡單的屬性語法。These two usages are somewhat uncommon, because each of these cases could also use a simpler attribute syntax. 以字串填滿屬性專案的其中一個案例是針對不是 XAML 內容屬性,但仍用於表示 UI 文字的屬性,而特定的空白字元(例如,分行符號)必須出現在該 UI 文字中。One scenario for filling a property element with a string is for properties that are not the XAML content property but still are used for representation of UI text, and particular white-space elements such as linefeeds are required to appear in that UI text. 屬性語法無法保留分行符號,但屬性專案語法可以,只要有效的空白字元保留作用(如需詳細資料,請參閱XAML 中的空白字元處理)。Attribute syntax cannot preserve linefeeds, but property element syntax can, so long as significant white-space preservation is active (for details, see White space processing in XAML). 另一個情況是,可以將x:Uid指示詞套用至 property 專案,因此會將中的值標示為應該在 WPF 輸出 BAML 或其他技術中當地語系化的值。Another scenario is so that x:Uid Directive can be applied to the property element and thus mark the value within as a value that should be localized in the WPF output BAML or by other techniques.

屬性元素不會在 WPF 邏輯樹狀結構中表示。A property element is not represented in the WPF logical tree. Property 元素只是用來設定屬性的特定語法,而且不是具有實例或物件支援的元素。A property element is just a particular syntax for setting a property, and is not an element that has an instance or object backing it. (如需邏輯樹狀概念的詳細資訊,請參閱WPF 中的樹狀結構)。(For details on the logical tree concept, see Trees in WPF.)

對於支援屬性和屬性專案語法的屬性而言,這兩個語法通常會有相同的結果,但微妙差異(例如空白字元處理)可能會在語法上稍有不同。For properties where both attribute and property element syntax are supported, the two syntaxes generally have the same result, although subtleties such as white-space handling can vary slightly between syntaxes.

集合語法Collection Syntax

XAML 規格需要 XAML 處理器執行,以識別實值型別為集合的屬性。The XAML specification requires XAML processor implementations to identify properties where the value type is a collection. .NET 中的一般 XAML 處理器執行是以 managed 程式碼和 CLR 為基礎,而且它會透過下列其中一項來識別集合類型:The general XAML processor implementation in .NET is based on managed code and the CLR, and it identifies collection types through one of the following:

如果屬性的類型是集合,則不需要在標記中將推斷的集合類型指定為 object 元素。If the type of a property is a collection, then the inferred collection type does not need to be specified in the markup as an object element. 相反地,要做為集合中專案的元素會指定為 property 元素的一或多個子項目。Instead, the elements that are intended to become the items in the collection are specified as one or more child elements of the property element. 每個這類專案會在載入時評估為物件,並藉由呼叫隱含集合的 Add 方法來新增至集合。Each such item is evaluated to an object during loading and added to the collection by calling the Add method of the implied collection. 例如,StyleTriggers 屬性會採用特殊化的集合型別 TriggerCollection,它會執行 IListFor example, the Triggers property of Style takes the specialized collection type TriggerCollection, which implements IList. 不需要在標記中具現化 TriggerCollection 物件元素。It is not necessary to instantiate a TriggerCollection object element in the markup. 相反地,您會將一或多個 Trigger 專案指定為 Style.Triggers property 元素中的元素,其中 Trigger (或衍生類別)是預期為強型別和隱含 TriggerCollection之專案類型的類型。Instead, you specify one or more Trigger items as elements within the Style.Triggers property element, where Trigger (or a derived class) is the type expected as the item type for the strongly typed and implicit TriggerCollection.

<Style x:Key="SpecialButton" TargetType="{x:Type Button}">
  <Style.Triggers>
    <Trigger Property="Button.IsMouseOver" Value="true">
      <Setter Property = "Background" Value="Red"/>
    </Trigger>
    <Trigger Property="Button.IsPressed" Value="true">
      <Setter Property = "Foreground" Value="Green"/>
    </Trigger>
  </Style.Triggers>
</Style>

屬性可以是集合類型,以及該類型和衍生類型的 XAML 內容屬性,這會在本主題的下一節中討論。A property may be both a collection type and the XAML content property for that type and derived types, which is discussed in the next section of this topic.

隱含的集合元素會在邏輯樹狀結構標記法中建立成員,即使它不會以專案形式出現在標記中。An implicit collection element creates a member in the logical tree representation, even though it does not appear in the markup as an element. 通常,父類型的函式會針對屬於其屬性之一的集合執行具現化,而初始空集合會成為物件樹狀結構的一部分。Usually the constructor of the parent type performs the instantiation for the collection that is one of its properties, and the initially empty collection becomes part of the object tree.

注意

不支援泛型清單和字典介面(IList<T>IDictionary<TKey,TValue>)進行集合偵測。The generic list and dictionary interfaces (IList<T> and IDictionary<TKey,TValue>) are not supported for collection detection. 不過,您可以使用 List<T> 類別做為基類,因為它會直接執行 IList,或當做基類來 Dictionary<TKey,TValue>,因為它會直接執行 IDictionaryHowever, you can use the List<T> class as a base class, because it implements IList directly, or Dictionary<TKey,TValue> as a base class, because it implements IDictionary directly.

在集合類型的 .NET 參考頁面中,XAML 語法區段偶爾會以隱含的集合語法的形式,將此語法視為集合的 object 元素。In the .NET Reference pages for collection types, this syntax with the deliberate omission of the object element for a collection is occasionally noted in the XAML syntax sections as Implicit Collection Syntax.

除了根項目之外,XAML 檔案中作為另一個專案之子專案的每個物件專案,實際上都是一個專案,也就是其父元素的隱含集合屬性的成員。,或指定父元素之 XAML 上下文屬性值的元素(即將在後續章節中討論 XAML 內容屬性)。With the exception of the root element, every object element in a XAML file that is nested as a child element of another element is really an element that is one or both of the following cases: a member of an implicit collection property of its parent element, or an element that specifies the value of the XAML content property for the parent element (XAML content properties will be discussed in an upcoming section). 換句話說,在標記頁面中,父元素和子專案的關聯性實際上是根目錄中的單一物件,而根目錄底下的每個物件專案都是單一實例,可提供父系的屬性值或一欄內的其中一個元素。observabledependencyobjectcollection 也是父系的集合型別屬性值。In other words, the relationship of parent elements and child elements in a markup page is really a single object at the root, and every object element beneath the root is either a single instance that provides a property value of the parent, or one of the items within a collection that is also a collection-type property value of the parent. 這個單一根目錄概念在 XML 中很常見,而且通常會在載入 XAML (例如 Load)的 Api 行為中加強。This single-root concept is common with XML, and is frequently reinforced in the behavior of APIs that load XAML such as Load.

下列範例是明確指定集合(GradientStopCollection)之 object 元素的語法。The following example is a syntax with the object element for a collection (GradientStopCollection) specified explicitly.

<LinearGradientBrush>  
  <LinearGradientBrush.GradientStops>  
    <GradientStopCollection>  
      <GradientStop Offset="0.0" Color="Red" />  
      <GradientStop Offset="1.0" Color="Blue" />  
    </GradientStopCollection>  
  </LinearGradientBrush.GradientStops>  
</LinearGradientBrush>  

請注意,不一定可以明確宣告集合。Note that it is not always possible to explicitly declare the collection. 例如,嘗試在先前顯示的 Triggers 範例中明確宣告 TriggerCollection 將會失敗。For instance, attempting to declare TriggerCollection explicitly in the previously shown Triggers example would fail. 明確宣告集合需要集合類別必須支援無參數的函式,而且 TriggerCollection 沒有無參數的函式。Explicitly declaring the collection requires that the collection class must support a parameterless constructor, and TriggerCollection does not have a parameterless constructor.

XAML 內容屬性XAML Content Properties

XAML 內容語法是一種語法,只有在指定 ContentPropertyAttribute 做為其類別宣告的一部分的類別上才會啟用。XAML content syntax is a syntax that is only enabled on classes that specify the ContentPropertyAttribute as part of their class declaration. ContentPropertyAttribute 會參考屬於該專案類型(包括衍生類別)之內容屬性的屬性名稱。The ContentPropertyAttribute references the property name that is the content property for that type of element (including derived classes). 由 XAML 處理器處理時,在物件專案的開頭和結束記號之間找到的任何子專案或內部文字,都會指派為該物件的 XAML 內容屬性值。When processed by a XAML processor, any child elements or inner text that are found between the opening and closing tags of the object element will be assigned to be the value of the XAML content property for that object. 您可以指定 content 屬性的明確屬性專案,但這種用法通常不會顯示在 .NET 參考的 XAML 語法區段中。You are permitted to specify explicit property elements for the content property, but this usage is not generally shown in the XAML syntax sections in the .NET reference. 明確/詳細的技巧偶爾會出現標記清晰度或標記樣式的值,但是內容屬性的目的通常是為了簡化標記,讓直覺相關的專案可以直接嵌套。The explicit/verbose technique has occasional value for markup clarity or as a matter of markup style, but usually the intent of a content property is to streamline the markup so that elements that are intuitively related as parent-child can be nested directly. 專案上其他屬性的屬性專案標記不會根據嚴格的 XAML 語言定義指派為「內容」;這些是先前在 XAML 剖析器的處理順序中處理,而且不會被視為「內容」。Property element tags for other properties on an element are not assigned as "content" per a strict XAML language definition; they are processed previously in the XAML parser's processing order and are not considered to be "content".

XAML 內容屬性值必須是連續的XAML Content Property Values Must Be Contiguous

XAML 內容屬性的值必須在該物件元素上的任何其他屬性專案之前或之後完整指定。The value of a XAML content property must be given either entirely before or entirely after any other property elements on that object element. 不論 XAML 內容屬性的值是指定為字串,還是一或多個物件,都是如此。This is true whether the value of a XAML content property is specified as a string, or as one or more objects. 例如,下列標記不會剖析:For example, the following markup does not parse:

<Button>I am a   
  <Button.Background>Blue</Button.Background>  
  blue button</Button>  

基本上,這是不合法的,因為如果使用 content 屬性的屬性專案語法來明確設定此語法,則會將 content 屬性設為兩次:This is illegal essentially because if this syntax were made explicit by using property element syntax for the content property, then the content property would be set twice:

<Button>  
  <Button.Content>I am a </Button.Content>  
  <Button.Background>Blue</Button.Background>  
  <Button.Content> blue button</Button.Content>  
</Button>  

同樣不合法的範例是,如果 content 屬性是一個集合,而子項目與屬性專案交錯:A similarly illegal example is if the content property is a collection, and child elements are interspersed with property elements:

<StackPanel>  
  <Button>This example</Button>  
  <StackPanel.Resources>  
    <SolidColorBrush x:Key="BlueBrush" Color="Blue"/>  
  </StackPanel.Resources>  
  <Button>... is illegal XAML</Button>  
</StackPanel>  

內容屬性和集合語法合併Content Properties and Collection Syntax Combined

為了接受一個以上的物件元素做為內容,content 屬性的類型必須特別是集合類型。In order to accept more than a single object element as content, the type of the content property must specifically be a collection type. 類似于集合類型的屬性元素語法,XAML 處理器必須識別屬於集合類型的類型。Similar to property element syntax for collection types, a XAML processor must identify types that are collection types. 如果專案具有 XAML 內容屬性,而且 XAML 內容屬性的類型是集合,則隱含的集合類型不需要在標記中指定為物件元素,而且 XAML 內容屬性不需要指定為 el 屬性。& e).If an element has a XAML content property and the type of the XAML content property is a collection, then the implied collection type does not need to be specified in the markup as an object element and the XAML content property does not need to be specified as a property element. 因此,標記中的明顯內容模型現在可以將一個以上的子項目指派為內容。Therefore the apparent content model in the markup can now have more than one child element assigned as the content. 以下是 Panel 衍生類別的內容語法。The following is content syntax for a Panel derived class. 所有 Panel 衍生類別都會建立要 Children的 XAML 內容屬性,這需要 UIElementCollection類型的值。All Panel derived classes establish the XAML content property to be Children, which requires a value of type UIElementCollection.

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  >
  <StackPanel>
    <Button>Button 1</Button>
    <Button>Button 2</Button>
    <Button>Button 3</Button>
  </StackPanel>
</Page>

請注意,標記中不需要 Children 的屬性元素,也不需要 UIElementCollection 的元素。Note that neither the property element for Children nor the element for the UIElementCollection is required in the markup. 這是 XAML 的設計功能,如此一來,定義 UIUI 的遞迴包含專案,就能以具有直接父子式專案關聯性的嵌套元素樹狀結構來表示,而不需要有中間的屬性專案標記或集合物件。This is a design feature of XAML so that recursively contained elements that define a UIUI are more intuitively represented as a tree of nested elements with immediate parent-child element relationships, without intervening property element tags or collection objects. 事實上,根據設計,UIElementCollection 無法在標記中明確指定為物件元素。In fact, UIElementCollection cannot be specified explicitly in markup as an object element, by design. 因為其僅適用于隱含集合,所以 UIElementCollection 不會公開公用無參數的函式,因此無法將它具現化為物件元素。Because its only intended use is as an implicit collection, UIElementCollection does not expose a public parameterless constructor and thus cannot be instantiated as an object element.

使用 Content 屬性來混合物件中的屬性元素和物件元素Mixing Property Elements and Object Elements in an Object with a Content Property

XAML 規格宣告 XAML 處理器可以強制執行用來填入物件專案內 XAML 內容屬性的物件專案,必須是連續的,而且不能是混合的。The XAML specification declares that a XAML processor can enforce that object elements that are used to fill the XAML content property within an object element must be contiguous, and must not be mixed. WPFWPF XAML 處理器會強制執行這項與混合屬性元素和內容的限制。This restriction against mixing property elements and content is enforced by the WPFWPF XAML processors.

您可以將子物件元素做為物件元素中的第一個立即標記。You can have a child object element as the first immediate markup within an object element. 然後您可以引進屬性元素。Then you can introduce property elements. 或者,您可以指定一或多個屬性專案、[內容]、[其他] 屬性專案。Or, you can specify one or more property elements, then content, then more property elements. 但是一旦屬性專案遵循內容,您就無法再引進任何進一步的內容,您只能加入屬性專案。But once a property element follows content, you cannot introduce any further content, you can only add property elements.

此內容/屬性專案順序需求不適用於作為內容的內部文字。This content / property element order requirement does not apply to inner text used as content. 不過,它仍然是讓內部文字保持連續的良好標記樣式,因為如果屬性專案與內部文字交錯,明顯的空白字元將難以在標記中以視覺方式偵測。However, it is still a good markup style to keep inner text contiguous, because significant white space will be difficult to detect visually in the markup if property elements are interspersed with inner text.

XAML 命名空間XAML Namespaces

上述語法範例都不會指定預設 XAML 命名空間以外的 XAML 命名空間。None of the preceding syntax examples specified a XAML namespace other than the default XAML namespace. 在一般 WPFWPF 應用程式中,預設的 XAML 命名空間會指定為 WPFWPF 命名空間。In typical WPFWPF applications, the default XAML namespace is specified to be the WPFWPF namespace. 除了預設的 XAML 命名空間以外,您還可以指定 XAML 命名空間,而且仍然會使用類似的語法。You can specify XAML namespaces other than the default XAML namespace and still use similar syntax. 但是,在預設的 XAML 命名空間中無法存取名為的類別的任何地方,該類別名稱前面必須加上 XAML 命名空間的前置詞,以便對應至對應的 CLR 命名空間。But then, anywhere where a class is named that is not accessible within the default XAML namespace, that class name must be preceded with the prefix of the XAML namespace as mapped to the corresponding CLR namespace. 例如,<custom:Example/> 是物件專案語法,用來具現化 Example 類別的實例,其中包含該類別的 CLR 命名空間(可能是包含支援類型的外部元件資訊)先前已對應至 custom前置詞.For example, <custom:Example/> is object element syntax to instantiate an instance of the Example class, where the CLR namespace containing that class (and possibly the external assembly information that contains backing types) was previously mapped to the custom prefix.

如需 XAML 命名空間的詳細資訊,請參閱WPF xaml 的 Xaml 命名空間和命名空間對應For more information about XAML namespaces, see XAML Namespaces and Namespace Mapping for WPF XAML.

標記延伸Markup Extensions

XAML 會定義標記延伸程式設計實體,讓您可以從標準的 XAML 處理器處理字串屬性值或物件專案,並將處理延遲到支援類別。XAML defines a markup extension programming entity that enables an escape from the normal XAML processor handling of string attribute values or object elements, and defers the processing to a backing class. 使用屬性語法時,識別 XAML 處理器之標記延伸的字元是左大括弧({),後面接著右大括弧(})以外的任何字元。The character that identifies a markup extension to a XAML processor when using attribute syntax is the opening curly brace ({), followed by any character other than a closing curly brace (}). 左大括弧後面的第一個字串必須參考提供特定延伸模組行為的類別,如果該子字串是真正類別名稱的一部分,參考可能會省略子字串 "Extension"。The first string following the opening curly brace must reference the class that provides the particular extension behavior, where the reference may omit the substring "Extension" if that substring is part of the true class name. 之後,就會出現一個空格,然後將每個後續字元當做延伸模組實作為輸入使用,直到遇到右大括弧為止。Thereafter, a single space may appear, and then each succeeding character is used as input by the extension implementation, up until the closing curly brace is encountered.

.NET XAML 執行會使用 MarkupExtension 抽象類別,做為 WPFWPF 和其他架構或技術支援的所有標記延伸的基礎。The .NET XAML implementation uses the MarkupExtension abstract class as the basis for all of the markup extensions supported by WPFWPF as well as other frameworks or technologies. WPFWPF 特別執行的標記延伸通常是用來提供參考其他現有物件的方法,或對將在執行時間評估的物件進行延遲的參考。The markup extensions that WPFWPF specifically implements are often intended to provide a means to reference other existing objects, or to make deferred references to objects that will be evaluated at run time. 例如,藉由指定 {Binding} 標記延伸來取代特定屬性通常會採用的值,即可完成簡單的 WPF 資料系結。For example, a simple WPF data binding is accomplished by specifying the {Binding} markup extension in place of the value that a particular property would ordinarily take. 許多 WPF 標記延伸都會啟用屬性的屬性語法,在此情況下不可能發生屬性語法。Many of the WPF markup extensions enable an attribute syntax for properties where an attribute syntax would not otherwise be possible. 例如,Style 物件是相當複雜的類型,其中包含一組嵌套的物件和屬性。For example, a Style object is a relatively complex type that contains a nested series of objects and properties. WPF 中的樣式通常會定義為 ResourceDictionary中的資源,然後透過兩個要求資源的 WPF 標記延伸其中之一來參考。Styles in WPF are typically defined as a resource in a ResourceDictionary, and then referenced through one of the two WPF markup extensions that request a resource. 標記延伸會將屬性值的評估延遲到資源查閱,並可在屬性語法中提供 Style 屬性的值,採用類型 Style,如下列範例所示:The markup extension defers the evaluation of the property value to a resource lookup and enables providing the value of the Style property, taking type Style, in attribute syntax as in the following example:

<Button Style="{StaticResource MyStyle}">My button</Button>

在這裡,StaticResource 識別提供標記延伸實作為的 StaticResourceExtension 類別。Here, StaticResource identifies the StaticResourceExtension class providing the markup extension implementation. 下一個字串 MyStyle 是做為非預設 StaticResourceExtension 的函式的輸入,其中從延伸模組字串取得的參數會宣告要求的 ResourceKeyThe next string MyStyle is used as the input for the non-default StaticResourceExtension constructor, where the parameter as taken from the extension string declares the requested ResourceKey. MyStyle 應該是定義為資源之 Stylex:Key值。MyStyle is expected to be the x:Key value of a Style defined as a resource. StaticResource 標記延伸使用方式會要求資源透過靜態資源查閱邏輯,在載入時用來提供 Style 屬性值。The StaticResource Markup Extension usage requests that the resource be used to provide the Style property value through static resource lookup logic at load time.

如需標記延伸的詳細資訊,請參閱標記延伸和 WPF XAMLFor more information about markup extensions, see Markup Extensions and WPF XAML. 如需在一般 .NET XAML 執行中啟用的標記延伸和其他 XAML 程式設計功能的參考,請參閱XAML 命名空間(x:)語言功能For a reference of markup extensions and other XAML programming features enabled in the general .NET XAML implementation, see XAML Namespace (x:) Language Features. 如需 WPF 特定的標記延伸,請參閱WPF XAML 延伸模組。For WPF-specific markup extensions, see WPF XAML Extensions.

附加屬性Attached Properties

附加屬性是 XAML 中引進的程式設計概念,其中的屬性可由特定類型所擁有和定義,但設定為任何專案上的屬性或屬性專案。Attached properties are a programming concept introduced in XAML whereby properties can be owned and defined by a particular type, but set as attributes or property elements on any element. 附加屬性的主要案例是讓標記結構中的子專案向父項目報告資訊,而不需要在所有專案上有廣泛的共用物件模型。The primary scenario that attached properties are intended for is to enable child elements in a markup structure to report information to a parent element without requiring an extensively shared object model across all elements. 相反地,父元素也可以使用附加屬性,將資訊報告至子項目。Conversely, attached properties can be used by parent elements to report information to child elements. 如需附加屬性的用途,以及如何建立您自己的附加屬性的詳細資訊,請參閱附加屬性總覽For more information on the purpose of attached properties and how to create your own attached properties, see Attached Properties Overview.

附加屬性會使用表面上類似屬性專案語法的語法,您也可以指定typeNamepropertyName組合。Attached properties use a syntax that superficially resembles property element syntax, in that you also specify a typeName.propertyName combination. 有兩個重大差異:There are two important differences:

  • 您可以使用typeNamepropertyName組合,即使是透過屬性語法設定附加屬性時也一樣。You can use the typeName.propertyName combination even when setting an attached property through attribute syntax. 附加屬性是限定屬性名稱是屬性語法需求的唯一案例。Attached properties are the only case where qualifying the property name is a requirement in an attribute syntax.

  • 您也可以使用附加屬性的屬性專案語法。You can also use property element syntax for attached properties. 不過,針對一般屬性專案語法,您指定的typeName是包含 property 專案的 object 元素。However, for typical property element syntax, the typeName you specify is the object element that contains the property element. 如果您要參考附加屬性,則typeName是定義附加屬性的類別,而不是包含的 object 元素。If you are referring to an attached property, then the typeName is the class that defines the attached property, not the containing object element.

附加事件Attached Events

附加事件是 XAML 中引進的另一種程式設計概念,其中事件可以由特定類型定義,但處理常式可以附加至任何物件元素。Attached events are another programming concept introduced in XAML where events can be defined by a specific type, but handlers may be attached on any object element. 在 WOF 的執行中,定義附加事件的類型通常是定義服務的靜態類型,有時這些附加事件是由公開服務之類型中的路由事件別名所公開。In the WOF implementation, often the type that defines an attached event is a static type that defines a service, and sometimes those attached events are exposed by a routed event alias in types that expose the service. 附加事件的處理常式是透過屬性語法來指定。Handlers for attached events are specified through attribute syntax. 如同附加事件,已針對附加事件展開屬性語法以允許typeName事件名稱的使用方式,其中typeName是提供 Add 的類別,並 Remove 附加事件基礎結構的事件處理常式存取子 ,而事件名稱為。As with attached events, the attribute syntax is expanded for attached events to allow a typeName.eventName usage, where typeName is the class that provides Add and Remove event handler accessors for the attached event infrastructure, and eventName is the event name.

XAML 根項目的剖析Anatomy of a XAML Root Element

下表顯示一般 XAML 根項目的細分,其中顯示根項目的特定屬性:The following table shows a typical XAML root element broken down, showing the specific attributes of a root element:

<Page 開啟根項目的 object 元素Opening object element of the root element
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 預設(WPFWPF) XAML 命名空間The default (WPFWPF) XAML namespace
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" XAML 語言 XAML 命名空間The XAML language XAML namespace
x:Class="ExampleNamespace.ExampleCode" 將標記連接至為部分類別定義之任何程式碼後置的部分類別宣告The partial class declaration that connects markup to any code-behind defined for the partial class
> 根之物件元素的結尾。End of object element for the root. 物件尚未關閉,因為元素包含子項目Object is not closed yet because the element contains child elements

選擇性和非建議 XAML 用法Optional and Nonrecommended XAML Usages

下列各節描述 XAML 處理器在技術上支援的 XAML 用法,但會產生詳細資訊或其他美觀問題,當您開發包含 XAML 來源的應用程式時,會干擾 XAML 檔案的其餘部分。The following sections describe XAML usages that are technically supported by XAML processors, but that produce verbosity or other aesthetic issues that interfere with XAML files remaining human-readable when you develop applications that contain XAML sources.

選擇性的屬性元素使用方式Optional Property Element Usages

選擇性的屬性專案用法包括明確地寫出 XAML 處理器視為隱含的元素內容屬性。Optional property element usages include explicitly writing out element content properties that the XAML processor considers implicit. 例如,當您宣告 Menu的內容時,您可以選擇將 MenuItems 集合明確宣告為 <Menu.Items> 屬性專案標記,並將每個 MenuItem 放在 <Menu.Items>,而不是使用隱含的 XAML 處理器行為,Menu 的所有子項目都必須是 MenuItem,而且會放在 Items 集合中。For example, when you declare the contents of a Menu, you could choose to explicitly declare the Items collection of the Menu as a <Menu.Items> property element tag, and place each MenuItem within <Menu.Items>, rather than using the implicit XAML processor behavior that all child elements of a Menu must be a MenuItem and are placed in the Items collection. 有時候選擇性的用法有助於以視覺化方式澄清標記中所表示的物件結構。Sometimes the optional usages can help to visually clarify the object structure as represented in the markup. 或有時明確的屬性專案使用方式可以避免在技術上功能上的標記,但在視覺上令人困惑,例如屬性值內的嵌套標記延伸。Or sometimes an explicit property element usage can avoid markup that is technically functional but visually confusing, such as nested markup extensions within an attribute value.

完整 typeName。成員資格限定屬性Full typeName.memberName Qualified Attributes

TypeName。屬性的成員名稱格式實際上比路由事件案例的運作方式更為普遍。The typeName.memberName form for an attribute actually works more universally than just the routed event case. 但在其他情況下,表單是多餘的,而且您應該避免這種情況,因為這是因為標記樣式和可讀性的原因。But in other situations that form is superfluous and you should avoid it, if only for reasons of markup style and readability. 在下列範例中,Background 屬性的三個參考都完全相同:In the following example, each of the three references to the Background attribute are completely equivalent:

<Button Background="Blue">Background</Button>
<Button Button.Background="Blue">Button.Background</Button>
<Button Control.Background="Blue">Control.Background</Button>

Button.Background 有效,因為 Button 上該屬性的限定查閱成功(Background 繼承自 Control),而且 Button 是 object 元素或基類的類別。Button.Background works because the qualified lookup for that property on Button is successful (Background was inherited from Control) and Button is the class of the object element or a base class. Control.Background 可以運作,因為 Control 類別實際上會定義 Background,而 ControlButton 基類。Control.Background works because the Control class actually defines Background and Control is a Button base class.

不過,下列類型名稱為。成員名稱表單範例無法運作,因此會顯示為批註:However, the following typeName.memberName form example does not work and is thus shown commented:

<!--<Button Label.Background="Blue">Does not work</Button> -->

LabelControl的另一個衍生類別,而且如果您已在 Label 物件專案中指定 Label.Background,這項使用方式將會有作用。Label is another derived class of Control, and if you had specified Label.Background within a Label object element, this usage would have worked. 不過,因為 Label 不是 Button的類別或基類,所以指定的 XAML 處理器行為會接著處理 Label.Background 做為附加屬性。However, because Label is not the class or base class of Button, the specified XAML processor behavior is to then process Label.Background as an attached property. Label.Background 不是可用的附加屬性,而且此使用方式失敗。Label.Background is not an available attached property, and this usage fails.

基. 成員名稱屬性元素baseTypeName.memberName Property Elements

以類似的方式來使用typeName成員名稱形式適用于屬性語法,也就是成員名稱語法適用于屬性元素語法。In an analogous way to how the typeName.memberName form works for attribute syntax, a baseTypeName.memberName syntax works for property element syntax. 例如,下列語法可運作:For instance, the following syntax works:

<Button>Control.Background PE
  <Control.Background>
    <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
      <GradientStop Color="Yellow" Offset="0.0" />
      <GradientStop Color="LimeGreen" Offset="1.0" />
    </LinearGradientBrush>
    </Control.Background>
</Button>

在這裡,即使屬性專案已包含在 Button中,屬性專案還是會指定為 Control.BackgroundHere, the property element was given as Control.Background even though the property element was contained in Button.

但是就像typeName一樣。屬性的成員名稱形式,成員名稱在標記中的樣式不佳,您應該避免這個情況。But just like typeName.memberName form for attributes, baseTypeName.memberName is poor style in markup, and you should avoid it.

請參閱See also