# XAML 語法詳細資料XAML Syntax In Detail

## 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 專案的類別繼承行為，是從 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

• 元素和標記必須以正斜線（/）關閉，後面緊接著右角括弧（>）。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="CheckoutButton"/>


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


## 物件元素的屬性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.

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

### 屬性值的處理Processing of Attribute Values

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.

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


## 屬性元素語法Property Element Syntax

<Button>
Right-click me!</Button>


## 集合語法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:

<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>


<LinearGradientBrush>


## 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>


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


<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

<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>


### 使用 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.

## 標記延伸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>

## 附加屬性Attached Properties

• 您可以使用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.

## XAML 根項目的剖析Anatomy of a XAML 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

### 完整 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.

<!--<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

<Button>Control.Background PE
<Control.Background>