XAML 總覽 (WPF)XAML overview (WPF)

本主題說明 XAML 語言的功能,並示範如何使用 XAML 撰寫 Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) 應用程式。This topic describes the features of the XAML language and demonstrates how you can use XAML to write Windows Presentation Foundation (WPF)Windows Presentation Foundation (WPF) applications. 本主題特別針對以 WPFWPF 實作的 XAML 進行描述。This topic specifically describes XAML as implemented by WPFWPF. 就語言概念而言,XAML 本身涵蓋的範圍比 WPFWPF 還要廣。XAML itself is a larger language concept than WPFWPF.

何謂 XAML?What is XAML?

XAML 是一種宣告式的標記語言。XAML is a declarative markup language. XAML 適用于 .NET Framework 的程式設計模型, 可簡化 .NET Framework UIUI應用程式的建立。As applied to the .NET Framework programming model, XAML simplifies creating a UIUI for a .NET Framework application. 您可以在宣告UIUI式 XAML 標記中建立可見的UIUI元素, 然後使用透過部分類別定義聯結至標記的程式碼後置檔案, 將定義與執行時間邏輯隔開。You can create visible UIUI elements in the declarative XAML markup, and then separate the UIUI definition from the run-time logic by using code-behind files that are joined to the markup through partial class definitions. XAML 會以組件中定義的一組支援型別,直接表示物件的執行個體化。XAML directly represents the instantiation of objects in a specific set of backing types defined in assemblies. 這一點有別於其他大部分的標記語言,通常大部分的標記語言是與支援型別系統沒有此種直接關連的直譯式語言。This is unlike most other markup languages, which are typically an interpreted language without such a direct tie to a backing type system. XAML 會啟用工作流程,其中個別獨立的人員因而能夠使用不同的工具,操作應用程式的 UIUI 與邏輯。XAML enables a workflow where separate parties can work on the UIUI and the logic of an application, using potentially different tools.

XAML 檔案以文字表示時,則為通常有 .xaml 副檔名的 XML 檔案。When represented as text, XAML files are XML files that generally have the .xaml extension. 這些檔案可以採用任何 XML 編碼,但通常會採用 UTF-8 編碼。The files can be encoded by any XML encoding, but encoding as UTF-8 is typical.

下列範例示範如何建立按鈕作為 UIUI 的一部分。The following example shows how you might create a button as part of a UIUI. 這個範例只是讓您一窺 XAML 如何呈現常用的 UIUI 程式設計共通法則,並不是完整的範例。This example is just intended to give you a flavor of how XAML represents common UIUI programming metaphors (it is not a complete sample).

<StackPanel>
  <Button Content="Click Me"/>
</StackPanel>

Brief 中的 XAML 語法XAML syntax in brief

下列各節說明 XAML 語法的基本形式,並提供簡短的標記範例。The following sections explain the basic forms of XAML syntax, and give a short markup example. 這些章節的目的並不在於提供每一種語法格式的相關完整資訊,例如在支援型別系統中的呈現方式。These sections are not intended to provide complete information about each syntax form, such as how these are represented in the backing type system. 如需這個主題所涵蓋每一種語法格式之特定 XAML 語法特點的詳細資訊,請參閱 XAML 語法詳細資料For more information about the specifics of XAML syntax for each of the syntax forms introduced in this topic, see XAML Syntax In Detail.

若您之前已經熟悉 XML 語言,則下面幾節中的大部分內容對您而言都很簡單。Much of the material in the next few sections will be elementary to you, if you have previous familiarity with the XML language. 這是因為 XAML 的其中一個基本設計原則所致。This is a consequence of one of the basic design principles of XAML. XAML 語言會定義它自己的概念, 但這些概念會在 XML 語言和標記表單中工作。The XAML language defines concepts of its own, but these concepts work within the XML language and markup form.

XAML 物件元素XAML object elements

物件元素通常會宣告型別的執行個體。An object element typically declares an instance of a type. 該型別定義於組件中,而這些組件會為使用 XAML 語言的技術提供支援型別。That type is defined in the assemblies that provide the backing types for a technology that uses XAML as a language.

物件元素語法一定是以左角括弧 (<) 開始。Object element syntax always starts with an opening angle bracket (<). 之後接著您要用於建立執行個體之型別的名稱This is followed by the name of the type where you want to create an instance. (這個名稱可能會包含前置詞;前置詞的概念將於稍後說明)。接著,可以選擇性地在物件元素上宣告屬性。(The name can possibly include a prefix, a concept that will be explained later.) After this, you can optionally declare attributes on the object element. 然後,以右角括弧 (>) 結束,即可完成物件元素標記。To complete the object element tag, end with a closing angle bracket (>). 您也可以透過正斜線加上右角括弧 (/ >) 的組合完成標記,改為使用不含任何內容的自我結尾格式。You can instead use a self-closing form that does not have any content, by completing the tag with a forward slash and closing angle bracket in succession (/>). 例如,請回顧先前示範的標記程式碼片段:For example, look at the previously shown markup snippet again:

<StackPanel>
  <Button Content="Click Me"/>
</StackPanel>

此範例指定兩個物件元素:<StackPanel> (含內容且其後接著結束標記) 以及 <Button .../> (自我結尾格式,具有數個屬性)。This specifies two object elements: <StackPanel> (with content, and a closing tag later), and <Button .../> (the self-closing form, with several attributes). 物件元素 StackPanelButton 會個別對應到的類別名稱,是由 WPFWPF 所定義的,並會作為 WPFWPF 組件的一部分。The object elements StackPanel and Button each map to the name of a class that is defined by WPFWPF and is part of the WPFWPF assemblies. 當您指定物件元素標記時,您會建立 XAML 處理指示以建立新的執行個體。When you specify an object element tag, you create an instruction for XAML processing to create a new instance. 在剖析和載入 XAML 時, 會藉由呼叫基礎類型的無參數函式來建立每個實例。Each instance is created by calling the parameterless constructor of the underlying type when parsing and loading the XAML.

屬性語法 (屬性)Attribute syntax (properties)

物件的屬性 (Property) 通常能夠以物件元素的屬性 (Attribute) 來表示。Properties of an object can often be expressed as attributes of the object element. 屬性 (Attribute) 語法會命名在屬性 (Attribute) 語法中設定的屬性 (Property),並且緊接著指派運算子 (=)。An attribute syntax names the property that is being set in attribute syntax, followed by the assignment operator (=). 屬性 (Attribute) 的值一定是以利用引號括住的字串指定。The value of an attribute is always specified as a string that is contained within quotation marks.

對於過去曾經使用標記語言的開發人員而言,屬性 (Attribute) 語法是最有效率的屬性 (Property) 設定語法,也是最為直覺化的使用語法。Attribute syntax is the most streamlined property setting syntax and is the most intuitive syntax to use for developers who have used markup languages in the past. 舉例來說,下列標記建立的按鈕會以藍底紅字顯示 Content 所指定的文字。For example, the following markup creates a button that has red text and a blue background in addition to display text specified as Content.

<Button Background="Blue" Foreground="Red" Content="This is a button"/>

屬性元素語法Property element syntax

對於物件元素的某些屬性 (Property) 而言,屬性 (Attribute) 語法並不適用,這是因為在屬性 (Attribute) 語法的引號與字串限制下,無法適當表達提供屬性 (Property) 值所需的物件和資訊。For some properties of an object element, attribute syntax is not possible, because the object or information necessary to provide the property value cannot be adequately expressed within the quotation mark and string restrictions of attribute syntax. 對於這種情況,可以使用另一種稱為屬性 (Property) 元素語法的語法。For these cases, a different syntax known as property element syntax can be used.

屬性 (Property) 元素開始標記的語法是 <typeName.propertyName>The syntax for the property element start tag is <typeName.propertyName>. 一般而言, 該標記的內容是屬性作為其值之類型的物件元素。Generally, the content of that tag is an object element of the type that the property takes as its value. 指定內容之後, 您必須以結束標記關閉屬性專案。After specifying the content, you must close the property element with an end tag. 結束標記的語法則是 </typeName.propertyName>The syntax for the end tag is </typeName.propertyName>.

若可以使用屬性 (Attribute) 語法,則使用屬性 (Attribute) 語法通常比較方便,並且可以讓標記 (Markup) 更為精簡,不過這通常只是樣式上的問題,而非技術上的限制。If an attribute syntax is possible, using the attribute syntax is typically more convenient and enables a more compact markup, but that is often just a matter of style, not a technical limitation. 下列範例顯示的屬性 (Property) 會設定成跟上述屬性 (Attribute) 語法範例相同,但這次會對 Button 的所有屬性 (Property) 使用屬性 (Property) 元素語法。The following example shows the same properties being set as in the previous attribute syntax example, but this time by using property element syntax for all properties of the Button.

<Button>
  <Button.Background>
    <SolidColorBrush Color="Blue"/>
  </Button.Background>
  <Button.Foreground>
    <SolidColorBrush Color="Red"/>
  </Button.Foreground>
  <Button.Content>
    This is a button
  </Button.Content>
</Button>

集合語法Collection syntax

XAML 語言包含一些最佳化特色,能夠產生可讀性更高的標記。The XAML language includes some optimizations that produce more human-readable markup. 其中一項最佳化特點就是,如果特定屬性 (Property) 採用集合型別,那麼您於標記中宣告為該屬性值之子元素的項目,就會變成該集合的一部分。One such optimization is that if a particular property takes a collection type, then items that you declare in markup as child elements within that property's value become part of the collection. 在此情況下,子物件元素的集合會成為要設定給該集合屬性的值。In this case a collection of child object elements is the value being set to the collection property.

下列範例顯示設定GradientStops屬性值的集合語法:The following example shows collection syntax for setting values of the GradientStops property:

<LinearGradientBrush>  
  <LinearGradientBrush.GradientStops>  
    <!-- no explicit new GradientStopCollection, parser knows how to find or create -->  
    <GradientStop Offset="0.0" Color="Red" />  
    <GradientStop Offset="1.0" Color="Blue" />  
  </LinearGradientBrush.GradientStops>  
</LinearGradientBrush>  

XAML 內容屬性XAML content properties

XAML 指定了一個語言功能,類別可藉此確實指派其中一個屬性作為 XAML 內容屬性。XAML specifies a language feature whereby a class can designate exactly one of its properties to be the XAML content property. 該物件元素的子元素會用來設定該內容屬性的值。Child elements of that object element are used to set the value of that content property. 換言之,對於內容屬性而言 (其他類屬性則不適用),以 XAML 標記設定該屬性時,您可以省略屬性元素,進而在標記中產生更加明顯可見的父/子比喻。In other words, for the content property uniquely, you can omit a property element when setting that property in XAML markup and produce a more visible parent/child metaphor in the markup.

例如, Border會指定的Child內容屬性。For example, Border specifies a content property of Child. 下列兩個Border元素的處理方式相同。The following two Border elements are treated identically. 第一個利用內容屬性語法的優點,省略了 Border.Child 屬性元素。The first one takes advantage of the content property syntax and omits the Border.Child property element. 第二個則明確顯示 Border.ChildThe second one shows Border.Child explicitly.

<Border>  
  <TextBox Width="300"/>  
</Border>  
<!--explicit equivalent-->  
<Border>  
  <Border.Child>  
    <TextBox Width="300"/>  
  </Border.Child>  
</Border>  

根據 XAML 語言的規則,XAML 內容屬性值必須完全放在該物件元素上任何其他屬性元素之前或之後。As a rule of the XAML language, the value of a XAML content property must be given either entirely before or entirely after any other property elements on that object element. 例如,下列標記無法編譯:For instance, the following markup does not compile:

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

如需 XAML 內容屬性這項限制的詳細資訊,請參閱 XAML 語法詳細資料For more information about this restriction on XAML content properties, see the "XAML Content Properties" section of XAML Syntax In Detail.

文字內容Text content

少數 XAML 元素可以直接將文字作為其內容加以處理。A small number of XAML elements can directly process text as their content. 若要啟用這項功能,必須符合下列其中一種情況:To enable this, one of the following cases must be true:

  • 類別必須宣告 content 屬性, 而且該內容屬性必須是可指派給字串的類型 (此類型可能是Object)。The class must declare a content property, and that content property must be of a type assignable to a string (the type could be Object). ContentControl例如, 任何使用Content做為其 content 屬性且其為類型Object, 而這在實際ContentControl情況Button下支援下列使用方式, 例如: <Button>Hello</Button>For instance, any ContentControl uses Content as its content property and it is type Object, and this supports the following usage on a practical ContentControl such as a Button: <Button>Hello</Button>.

  • 該型別必須宣告型別轉換子,此時,文字內容便會作為該型別轉換子的初始設定文字。The type must declare a type converter, in which case the text content is used as initialization text for that type converter. 例如, <Brush>Blue</Brush>For example, <Brush>Blue</Brush>. 這種案例在實務中較不常見。This case is less common in practice.

  • 型別必須是已知的 XAML 語言基本型別。The type must be a known XAML language primitive.

內容屬性和集合語法的結合Content properties and collection syntax combined

請考量以下範例:Consider this example:

<StackPanel>  
  <Button>First Button</Button>  
  <Button>Second Button</Button>  
</StackPanel>  

在這裡, Button每個都是的StackPanel子項目。Here, each Button is a child element of StackPanel. 這段有效率而直覺化的標記 (Markup),是基於兩個不同理由省略兩個標記 (Tag)。This is a streamlined and intuitive markup that omits two tags for two different reasons.

<StackPanel>  
  <StackPanel.Children>  
    <!--<UIElementCollection>-->  
    <Button>First Button</Button>  
    <Button>Second Button</Button>  
    <!--</UIElementCollection>-->  
  </StackPanel.Children>  
</StackPanel>  

屬性語法 (事件)Attribute syntax (events)

屬性 (Attribute) 語法也可以供屬於事件而非屬性 (Property) 的成員使用。Attribute syntax can also be used for members that are events rather than properties. 在此情況下,屬性 (Attribute) 名稱就是事件名稱。In this case, the attribute's name is the name of the event. 在 WPF 的 XAML 事件實作中,屬性 (Attribute) 值會是實作該事件委派之事件處理常式的名稱。In the WPF implementation of events for XAML, the attribute's value is the name of a handler that implements that event's delegate. 例如, 下列標記會將Click事件的處理常式指派給在標記中建立的: ButtonFor example, the following markup assigns a handler for the Click event to a Button created in markup:

<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="ExampleNamespace.ExamplePage">
  <Button Click="Button_Click" >Click Me!</Button>
</Page>

除了這個屬性 (Attribute) 語法的範例,WPF 中還有更多事件與 XAML 的應用內容。There is more to events and XAML in WPF than just this example of the attribute syntax. 例如,您也許好奇在此所參照的 ClickHandler 究竟代表什麼以及它是如何定義的。For example, you might wonder what the ClickHandler referenced here represents and how it is defined. 本主題接下來的事件和 XAML 程式碼後置章節中便會詳加說明。This will be explained in the upcoming Events and XAML Code-Behind section of this topic.

XAML 中的大小寫和空白字元Case and white space in XAML

XAML 通常會區分大小寫。XAML is generally speaking case sensitive. 為了能夠解析支援型別,WPF XAML 會和 CLR 同樣遵守區分大小寫的規則。For purposes of resolving backing types, WPF XAML is case sensitive by the same rules that the CLR is case sensitive. 在依名稱與組件的基礎型別或與型別的成員進行比較時,物件元素、屬性 (Property) 元素和屬性 (Attribute) 名稱都必須以區分大小寫的方式指定。Object elements, property elements, and attribute names must all be specified by using the sensitive casing when compared by name to the underlying type in the assembly, or to a member of a type. XAML 語言關鍵字和基本型別也區分大小寫。XAML language keywords and primitives are also case sensitive. 值則不一定區分大小寫。Values are not always case sensitive. 值是否會區分大小寫的決定因素,在於採用該值的屬性 (Property) 或屬性 (Property) 值型別的相關型別轉換子行為。Case sensitivity for values will depend on the type converter behavior associated with the property that takes the value, or the property value type. 例如, 採用Boolean類型的屬性可以true採用或True做為對Boolean等的值, 但只是因為字串的原生 WPF XAML 剖析器類型轉換已允許使用這些專案。For example, properties that take the Boolean type can take either true or True as equivalent values, but only because the native WPF XAML parser type conversion for string to Boolean already permits these as equivalents.

WPF XAML 處理器和序列化程式會忽略或捨棄所有 nonsignificant 的空白字元, 並將任何顯著的空白字元正規化。WPF XAML processors and serializers will ignore or drop all nonsignificant white space, and will normalize any significant white space. 這與 XAML 規格的預設「空白字元」行為建議一致。This is consistent with the default white-space behavior recommendations of the XAML specification. 這個行為通常只不過是您在 XAML 內容屬性 (Property) 內指定字串的必然結果。This behavior is generally only of consequence when you specify strings within XAML content properties. 簡單地說,XAML 會將空白、換行字元和定位字元轉換成為空白,然後在連續字串兩端發現空白時保留一個空白。In simplest terms, XAML converts space, linefeed and tab characters into spaces, and then preserves one space if found at either end of a contiguous string. 本主題未涵蓋 XAML 空白字元處理的完整說明。The full explanation of XAML white-space handling is not covered in this topic. 如需詳細資訊, 請參閱XAML 中的空白字元處理。For details, see White space processing in XAML.

標記延伸Markup extensions

標記延伸是一種 XAML 語言的概念。Markup extensions are a XAML language concept. 大括號 ({}) 用於提供屬性 (Attribute) 語法的值時,表示的是一種標記延伸用法。When used to provide the value of an attribute syntax, curly braces ({ and }) indicate a markup extension usage. 這項使用會指引 XAML 處理跳脫一般的屬性 (Attribute) 值處理方式 (即視為常值字串或字串可轉換值)。This usage directs the XAML processing to escape from the general treatment of attribute values as either a literal string or a string-convertible value.

WPFWPF 應用程式設計中最常使用的標記延伸是 Binding (用於資料繫結運算式) 以及資源參考 StaticResourceDynamicResourceThe most common markup extensions used in WPFWPF application programming are Binding, used for data binding expressions, and the resource references StaticResource and DynamicResource. 使用標記延伸就可以使用屬性 (Attribute) 語法為屬性 (Property) 提供值,即使該屬性 (Property) 通常不支援屬性 (Attribute) 語法也一樣。By using markup extensions, you can use attribute syntax to provide values for properties even if that property does not support an attribute syntax in general. 標記延伸經常使用中繼運算式型別啟用延後值或參考其他物件這類僅出現在執行階段的功能。Markup extensions often use intermediate expression types to enable features such as deferring values or referencing other objects that are only present at run time.

例如, 下列標記會使用屬性語法來設定Style屬性的值。For example, the following markup sets the value of the Style property using attribute syntax. 屬性會採用Style類別的實例, 其預設無法由屬性語法字串具現化。 StyleThe Style property takes an instance of the Style class, which by default could not be instantiated by an attribute syntax string. 但在此情況下,屬性 (Attribute) 會參考特定的標記延伸 StaticResourceBut in this case, the attribute references a particular markup extension, StaticResource. 當處理該標記延伸時,所傳回的樣式參考先前是以資源字典中的調整資源來執行個體化。When that markup extension is processed, it returns a reference to a style that was previously instantiated as a keyed resource in a resource dictionary.

<Page.Resources>
  <SolidColorBrush x:Key="MyBrush" Color="Gold"/>
  <Style TargetType="Border" x:Key="PageBackground">
    <Setter Property="Background" Value="Blue"/>
  </Style>
</Page.Resources>
<StackPanel>
  <Border Style="{StaticResource PageBackground}">
  </Border>
</StackPanel>

如需 WPF 中特別實作之所有 XAML 標記延伸的參考清單,請參閱 WPF XAML 擴充功能For a reference listing of all markup extensions for XAML implemented specifically in WPF, see WPF XAML Extensions. 如需由 system.string 定義之標記延伸的參考清單, 以及更廣泛地提供 .NET Framework Xaml 執行功能的詳細資訊, 請參閱 xaml 命名空間 (x:)語言功能For a reference listing of the markup extensions that are defined by System.Xaml and are more widely available for .NET Framework XAML implementations, see XAML Namespace (x:) Language Features. 如需標記延伸概念的詳細資訊,請參閱標記延伸和 WPF XAMLFor more information about markup extension concepts, see Markup Extensions and WPF XAML.

類型轉換器Type converters

XAML 語法簡介一節中說明了屬性 (Attribute) 值必須要能夠由字串進行設定。In the XAML Syntax in Brief section, it was stated that the attribute value must be able to be set by a string. 除了特定類型String DateTime (例如或Uri) 的原生處理之外, 如何將字串轉換成其他物件類型或基本值的基本、原生處理也是以類型本身為基礎。The basic, native handling of how strings are converted into other object types or primitive values is based on the String type itself, in addition to native processing for certain types such as DateTime or Uri. 但是,這些型別的許多 WPFWPF 型別或成員會擴充基本字串屬性處理行為,使得更多複雜物件型別的執行個體能夠指定為字串與屬性。But many WPFWPF types or members of those types extend the basic string attribute processing behavior, in such a way that instances of more complex object types can be specified as strings and attributes.

Thickness結構是類型的範例, 其型別轉換已啟用 XAML 使用方式。The Thickness structure is an example of a type that has a type conversion enabled for XAML usages. Thickness表示在嵌套矩形內的測量, 並當做屬性的值使用, 例如MarginThickness indicates measurements within a nested rectangle and is used as the value for properties such as Margin. 藉由將類型轉換器放Thickness在上, 使用的Thickness所有屬性都可以在 XAML 中更容易指定, 因為它們可指定為屬性。By placing a type converter on Thickness, all properties that use a Thickness are easier to specify in XAML because they can be specified as attributes. 下列範例會使用類型轉換和屬性語法來提供的值Margin:The following example uses a type conversion and attribute syntax to provide a value for a Margin:

<Button Margin="10,20,10,30" Content="Click me"/>

先前的屬性語法範例相當於下列更詳細的語法範例, 其中Margin會改為透過Thickness包含 object 元素的屬性專案語法來設定。The previous attribute syntax example is equivalent to the following more verbose syntax example, where the Margin is instead set through property element syntax containing a Thickness object element. 的四個主要屬性Thickness會設定為新實例上的屬性:The four key properties of Thickness are set as attributes on the new instance:

<Button Content="Click me">
  <Button.Margin>
    <Thickness Left="10" Top="20" Right="10" Bottom="30"/>
  </Button.Margin>
</Button>

注意

也有少數的物件, 類型轉換是將屬性設定為該類型而不涉及子類別的唯一公用方式, 因為類型本身沒有無參數的函式。There are also a limited number of objects where the type conversion is the only public way to set a property to that type without involving a subclass, because the type itself does not have a parameterless constructor. 例如CursorAn example is Cursor.

如需如何支援型別轉換及其屬性 (Attribute) 語法用法的詳細資訊,請參閱 TypeConverters 和 XAMLFor more information on how type conversion and its use for attribute syntax is supported, see TypeConverters and XAML.

XAML 根項目和 XAML 命名空間XAML root elements and XAML namespaces

XAML 檔案只能有一個根元素,這樣才能同時成為語式正確的 XMLXML 檔案以及有效的 XAML 檔案。A XAML file must have only one root element, in order to be both a well-formed XMLXML file and a valid XAML file. 在一般 wpf 案例中, 您會使用在 WPF 應用程式模型中具有顯著意義的根項目 (例如, Window Page針對頁面、 ResourceDictionary針對外部字典, 或Application用於應用程式定義)。For typical WPF scenarios, you use a root element that has a prominent meaning in the WPF application model (for example, Window or Page for a page, ResourceDictionary for an external dictionary, or Application for the application definition). 下列範例會顯示WPFWPF頁面之一般 XAML 檔案的根項目, 其中根Page元素為。The following example shows the root element of a typical XAML file for a WPFWPF page, with the root element of Page.

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
</Page>

根元素也包含屬性 (Attribute) xmlnsxmlns:xThe root element also contains the attributes xmlns and xmlns:x. 這些屬性會向 XAML 處理器指出哪些 XAML 命名空間包含支援型別 (標記會將這些型別參考為元素) 的型別定義。These attributes indicate to a XAML processor which XAML namespaces contain the type definitions for backing types that the markup will reference as elements. xmlns 屬性會特別指出預設的 XAML 命名空間。The xmlns attribute specifically indicates the default XAML namespace. 在預設的 XAML 命名空間內,標記中的物件元素可以不使用前置詞指定。Within the default XAML namespace, object elements in the markup can be specified without a prefix. 對於大部分的 WPFWPF 應用程式案例,以及 SDKSDKWPFWPF 章節中提供的幾乎所有範例而言,預設 XAML 命名空間都會對應至 WPFWPF 命名空間 http://schemas.microsoft.com/winfx/2006/xaml/presentationFor most WPFWPF application scenarios, and for almost all of the examples given in the WPFWPF sections of the SDKSDK, the default XAML namespace is mapped to the WPFWPF namespace http://schemas.microsoft.com/winfx/2006/xaml/presentation. xmlns:x 屬性會指定另一個對應 XAML 語言命名空間 http://schemas.microsoft.com/winfx/2006/xaml 的命名空間。The xmlns:x attribute indicates an additional XAML namespace, which maps the XAML language namespace http://schemas.microsoft.com/winfx/2006/xaml.

使用 xmlns 定義命名空間使用和對應的範圍,與 XML 1.0 規格是一致的。This usage of xmlns to define a scope for usage and mapping of a namescope is consistent with the XML 1.0 specification. XAML 命名空間與 XML 命名空間唯一的差異在於,XAML 命名空間也帶有其他意涵,指出當涉及型別解析和剖析 XAML 時,型別會如何支援名稱範圍的元素。XAML namescopes are different from XML namescopes only in that a XAML namescope also implies something about how the namescope's elements are backed by types when it comes to type resolution and parsing the XAML.

請注意,每個 XAML 檔案的根元素才必須要有 xmlns 屬性。Note that the xmlns attributes are only strictly necessary on the root element of each XAML file. xmlns 定義會套用至根元素的所有子元素上 (這個行為再度與 xmlns 的 XML 1.0 規格一致)。xmlns 屬性也可以用在根元素底下的其他元素上,而且應該套用至定義元素下的任何子元素。xmlns definitions will apply to all descendant elements of the root element (this behavior is again consistent with the XML 1.0 specification for xmlns.) xmlns attributes are also permitted on other elements underneath the root, and would apply to any descendant elements of the defining element. 然而,過於頻繁地定義或重新定義 XAML 命名空間會造成 XAML 標記樣式難以閱讀。However, frequent definition or redefinition of XAML namespaces can result in a XAML markup style that is difficult to read.

其 XAML 處理器的 WPFWPF 實作包含能夠辨認 WPF 核心組件的基礎結構。The WPFWPF implementation of its XAML processor includes an infrastructure that has awareness of the WPF core assemblies. 廣為人知的一點是,WPFWPF 核心組件包含支援將 WPFWPF 對應至預設 XAML 命名空間的型別。The WPFWPF core assemblies are known to contain the types that support the WPFWPF mappings to the default XAML namespace. 這項功能可以透過屬於專案組建檔以及 WPF 組建與專案系統的組態進行啟用。This is enabled through configuration that is part of your project build file and the WPF build and project systems. 因此,必須將預設的 XAML 命名空間宣告為預設的 xmlns,才能夠參考來自 WPFWPF 組件的 XAML 元素。Therefore, declaring the default XAML namespace as the default xmlns is all that is necessary in order to reference XAML elements that come from WPFWPF assemblies.

X: 前置詞The x: prefix

在先前的根元素範例中,前置詞 x: 會用於對應 XAML 命名空間 http://schemas.microsoft.com/winfx/2006/xaml,它是支援 XAML 語言建構的專屬 XAML 命名空間。In the previous root element example, the prefix x: was used to map the XAML namespace http://schemas.microsoft.com/winfx/2006/xaml, which is the dedicated XAML namespace that supports XAML language constructs. 這個 x: 前置詞會用於對應範例中專案範本的這個 XAML 命名空間,同時整份 SDKSDK 說明文件中也會使用這個前置詞。This x: prefix is used for mapping this XAML namespace in the templates for projects, in examples, and in documentation throughout this SDKSDK. Xaml 語言的 XAML 命名空間包含數個在 XAML 中經常使用的程式設計結構。The XAML namespace for the XAML language contains several programming constructs that you will use very frequently in your XAML. 下列清單是您最常使用的 x: 前置詞程式設計建構:The following is a listing of the most common x: prefix programming constructs you will use:

  • x:Key:為中ResourceDictionary的每個資源設定唯一索引鍵 (或其他架構中的類似字典概念)。x:Key: Sets a unique key for each resource in a ResourceDictionary (or similar dictionary concepts in other frameworks). 您通常在 WPF 應用程式標記中看到的 x:,大概有 90% 都是 x:Keyx:Key will probably account for 90% of the x: usages you will see in a typical WPF application's markup.

  • x:Class:指定類別的 CLR 命名空間和類別名稱, 以提供 XAML 頁面的程式碼後置。x:Class: Specifies the CLR namespace and class name for the class that provides code-behind for a XAML page. 依據 WPF 程式撰寫模型,您必須有這類支援程式碼後置的類別,因此您幾乎都會看到 x: 對應,即使沒有資源也一樣。You must have such a class to support code-behind per the WPF programming model, and therefore you almost always see x: mapped, even if there are no resources.

  • x:Name:指定在處理物件專案之後, 存在於執行時間程式碼中之實例的執行時間物件名稱。x:Name: Specifies a run-time object name for the instance that exists in run-time code after an object element is processed. 一般而言,您經常會使用 WPF 針對 x:Name 所定義的對等屬性。In general, you will frequently use a WPF-defined equivalent property for x:Name. 這類屬性專門對應至 CLR 支援屬性,因此對於您經常會使用執行階段程式碼來尋找已初始化 XAML 中的具名元素的應用程式設計情境而言,會更方便。Such properties map specifically to a CLR backing property and are thus more convenient for application programming, where you frequently use run time code to find the named elements from initialized XAML. 最常見的這類屬性FrameworkElement.Name是。The most common such property is FrameworkElement.Name. 當特定類型中不支援對等的 WPF 架構層Name級屬性時, 您仍然可以使用 x:NameYou might still use x:Name when the equivalent WPF framework-level Name property is not supported in a particular type. 這會發生在某些動畫案例中。This occurs in certain animation scenarios.

  • x:Static:啟用會傳回靜態值的參考, 但不是以 XAML 相容的屬性。x:Static: Enables a reference that returns a static value that is not otherwise a XAML-compatible property.

  • x:Type:根據型Type別名稱來建立參考。x:Type: Constructs a Type reference based on a type name. 這是Type用來指定採用的屬性, Style.TargetType例如, 雖然屬性通常具有Type原生字串轉換, 但x:Type標記延伸使用方式是選擇性的。This is used to specify attributes that take Type, such as Style.TargetType, although frequently the property has native string-to-Type conversion in such a way that the x:Type markup extension usage is optional.

x: 前置詞/XAML 命名空間中還有其他的程式設計建構,但並不常用。There are additional programming constructs in the x: prefix/XAML namespace, which are not as common. 如需詳細資訊, 請參閱 XAML 命名空間 (x:)語言功能For details, see XAML Namespace (x:) Language Features.

XAML 中的自訂前置詞和自訂類型Custom prefixes and custom types in XAML

對於您自己的自訂組件或是 WPF 核心 (PresentationCore、PresentationFramework 與 WindowsBase) 以外的組件,您可以指定組件作為自訂 xmlns 對應的一部分。For your own custom assemblies, or for assemblies outside the WPF core of PresentationCore, PresentationFramework and WindowsBase, you can specify the assembly as part of a custom xmlns mapping. 接著,只要型別已正確實作為可以支援您嘗試進行的 XAML 用法,您便可以在您的 XAML 中參考該組件中的型別。You can then reference types from that assembly in your XAML, so long as that type is correctly implemented to support the XAML usages you are attempting.

下列範例為自訂前置詞在 XAML 標記中運作方式的基本範例。The following is a very basic example of how custom prefixes work in XAML markup. 前置詞 custom 會定義於根元素標記中,且對應到已封裝並隨應用程式提供的特定組件。The prefix custom is defined in the root element tag, and mapped to a specific assembly that is packaged and available with the application. 這個組件包含 NumericUpDown 型別,會實作該型別以支援一般的 XAML 用法,以及使用類別繼承,這個類別繼承允許在 WPF XAML 內容模型的特定點置中插入這個型別。This assembly contains a type NumericUpDown, which is implemented to support general XAML usage as well as using a class inheritance that permits its insertion at this particular point in a WPF XAML content model. 這個 NumericUpDown 控制項的執行個體會使用前置詞宣告為物件元素,如此一來,XAML 剖析器便能得知哪一個 XAML 命名空間包含型別,因此支援組件的所在便是包含型別定義的位置。An instance of this NumericUpDown control is declared as an object element, using the prefix so that a XAML parser knows which XAML namespace contains the type, and therefore where the backing assembly is that contains the type definition.

<Page  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
    xmlns:custom="clr-namespace:NumericUpDownCustomControl;assembly=CustomLibrary"  
    >  
  <StackPanel Name="LayoutRoot">  
    <custom:NumericUpDown Name="numericCtrl1" Width="100" Height="60"/>  
...  
  </StackPanel>  
</Page>  

如需 XAML 中自訂型別的詳細資訊,請參閱 WPF 的 XAML 和自訂類別For more information about custom types in XAML, see XAML and Custom Classes for WPF.

如需 XML 命名空間和組件中支援程式碼之命名空間的關聯方式的詳細資訊,請參閱 WPF XAML 的 XAML 命名空間和命名空間對應For more information about how XML namespaces and the namespaces of the backing code in assemblies are related, see XAML Namespaces and Namespace Mapping for WPF XAML.

事件和 XAML 程式碼後置Events and XAML code-behind

大部分的 WPFWPF 應用程式都同時由 XAML 標記和程式碼後置所組成。Most WPFWPF applications consist of both XAML markup and code-behind. 在專案內, XAML 會撰寫為.xaml檔案, 而 CLR 語言 (例如 Microsoft Visual Basic 或C# ) 則是用來撰寫程式碼後置檔案。Within a project, the XAML is written as a .xaml file, and a CLR language such as Microsoft Visual Basic or C# is used to write a code-behind file. 將 XAML 檔案作為 WPF 程式設計和應用程式模型的一部分而進行標記編譯時,XAML 檔案的 XAML 程式碼後置檔案的位置,是藉由指定命名空間和類別作為 XAML 根元素的 x:Class 屬性 (Attribute) 來識別。When a XAML file is markup compiled as part of the WPF programming and application models, the location of the XAML code-behind file for a XAML file is identified by specifying a namespace and class as the x:Class attribute of the root element of the XAML.

在目前的範例中,您已經看過幾種按鈕,但沒有一個按鈕具有任何相關聯的邏輯行為。In the examples so far, you have seen several buttons, but none of these buttons had any logical behavior associated with them yet. 用於新增物件元素行為的主要應用程式層級機制,是使用元素類別的現有事件,並為該事件撰寫在執行階段引發該事件時所叫用的特定處理常式。The primary application-level mechanism for adding a behavior for an object element is to use an existing event of the element class, and to write a specific handler for that event that is invoked when that event is raised at run time. 要使用的事件名稱和處理常式名稱是在標記中指定的,而實作處理常式的程式碼則是在程式碼後置中定義。The event name and the name of the handler to use are specified in the markup, whereas the code that implements your handler is defined in the code-behind.

<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="ExampleNamespace.ExamplePage">
  <Button Click="Button_Click" >Click Me!</Button>
</Page>
namespace ExampleNamespace
{
  public partial class ExamplePage
  {
    void Button_Click(object sender, RoutedEventArgs e)
    {
      Button b = e.Source as Button;
      b.Foreground = Brushes.Red;
    }
  }
}
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    Dim b As Button = e.Source
    b.Foreground = Brushes.Red
End Sub

請注意,程式碼後置檔案會使用 CLR 命名空間 ExampleNamespace,並宣告 ExamplePage 作為該命名空間內的部分類別。Notice that the code-behind file uses the CLR namespace ExampleNamespace and declares ExamplePage as a partial class within that namespace. 這等同于x:Class的屬性ExampleNamespace值。ExamplePageThis parallels the x:Class attribute value of ExampleNamespace.ExamplePage 在標記根目錄中提供。that was provided in the markup root. WPF 標記編譯器會藉由從根元素型別衍生類別,為任何編譯的 XAML 檔案建立部分類別。The WPF markup compiler will create a partial class for any compiled XAML file, by deriving a class from the root element type. 當您提供的程式碼後置也會定義相同的部分類別時,產生的程式碼會結合在已編譯應用程式的相同命名空間和類別內。When you provide code-behind that also defines the same partial class, the resulting code is combined within the same namespace and class of the compiled application.

如需 WPF 中程式碼後置程式設計之需求的詳細資訊,請參閱 WPF 中的程式碼後置和 XAML 的<程式碼後置、事件處理常式和部分類別需求>一節。For more information about requirements for code-behind programming in WPF, see the "Code-behind, Event Handler, and Partial Class Requirements" section of Code-Behind and XAML in WPF.

如果不想要建立獨立的程式碼後置檔案,您也可以在 XAML 檔案中內嵌程式碼。If you do not want to create a separate code-behind file, you can also inline your code in a XAML file. 然而,內嵌程式碼具有基本的限制,是一個用途較少的技術。However, inline code is a less versatile technique that has substantial limitations. 如需詳細資訊,請參閱 WPF 中的程式碼後置和 XAMLFor details, see Code-Behind and XAML in WPF.

路由事件Routed events

WPFWPF 來說有一個基本的特別事件功能,即為路由事件。A particular event feature that is fundamental to WPFWPF is a routed event. 路由事件可以讓元素處理由其他元素引發的事件,只要元素可以透過樹狀結構關係來連接即可。Routed events enable an element to handle an event that was raised by a different element, as long as the elements are connected through a tree relationship. 在使用 XAML 屬性 (Attribute) 指定事件處理時,路由事件可以由任何元素接聽和處理,包括類別成員表中沒有列出該特定事件的元素。When specifying event handling with a XAML attribute, the routed event can be listened for and handled on any element, including elements that do not list that particular event in the class members table. 這可以藉由使用主控類別名稱來限定事件名稱屬性而達成。This is accomplished by qualifying the event name attribute with the owning class name. StackPanel例如, 在進行StackPanel / StackPanel中的範例中, 父系可以藉由在上指定屬性Button.Click , 為Click子項目按鈕的事件註冊處理常式。 Buttonobject 元素, 其中以您的處理常式名稱作為屬性值。For instance, the parent StackPanel in the ongoing StackPanel / Button example could register a handler for the child element button's Click event by specifying the attribute Button.Click on the StackPanel object element, with your handler name as the attribute value. 如需路由事件運作方式的詳細資訊,請參閱路由事件概觀For more information about how routed events work, see Routed Events Overview.

XAML 命名元素XAML named elements

根據預設,藉由處理 XAML 物件元素而建立於物件圖形中的物件執行個體,並不會擁有唯一識別項或物件參考。By default, the object instance that is created in an object graph by processing a XAML object element does not possess a unique identifier or object reference. 相反地,如果在程式碼中呼叫建構函式,您幾乎都是使用建構函式結果來設定所建構執行個體的變數,這樣您可於稍後在程式碼中參考執行個體。In contrast, if you call a constructor in code, you almost always use the constructor result to set a variable to the constructed instance, so that you can reference the instance later in your code. 為了要對透過標記定義建立的物件提供標準化存取,XAML 定義了 x:Name 屬性In order to provide standardized access to objects that were created through a markup definition, XAML defines the x:Name attribute. 您可以對任何物件元素設定 x:Name 屬性值。You can set the value of the x:Name attribute on any object element. 在程式碼後置中,您選擇的識別項等同於代表所建構執行個體的執行個體變數。In your code-behind, the identifier you choose is equivalent to an instance variable that refers to the constructed instance. 就各方面來說,具名元素的運作方式就如同它們是物件執行個體一樣 (名稱會參考該執行個體),而您的程式碼後置可以參考具名元素來處理應用程式內的執行階段互動。In all respects, named elements function as if they were object instances (the name references that instance), and your code-behind can reference the named elements to handle run-time interactions within the application. 實例和變數之間的這個連接是由 WPF XAML 標記編譯器完成, 更明確地牽涉到這類InitializeComponent功能和模式, 這不會在本主題中詳細討論。This connection between instances and variables is accomplished by the WPF XAML markup compiler, and more specifically involve features and patterns such as InitializeComponent that will not be discussed in detail in this topic.

WPF 架構層級的 xaml 元素會Name繼承屬性, 這相當於 XAML 定義x:Name的屬性。WPF framework-level XAML elements inherit a Name property, which is equivalent to the XAML defined x:Name attribute. 某些其他類別也會提供 x:Name 的屬性 (Property) 層級對等用法,通常也會定義為 Name 屬性 (Property)。Certain other classes also provide property-level equivalents for x:Name, which is also generally defined as a Name property. 一般來說,如果在成員表中找不到您所選元素/型別的 Name 屬性 (Property),請改用 x:NameGenerally speaking, if you cannot find a Name property in the members table for your chosen element/type, use x:Name instead. 這些x:Name值會將識別碼提供給 XAML 專案, 此專案可由特定子系統或公用程式方法 (例如) FindName在執行時間使用。The x:Name values will provide an identifier to a XAML element that can be used at run time, either by specific subsystems or by utility methods such as FindName.

下列範例會StackPanelName元素上設定。The following example sets Name on a StackPanel element. 然後, Button在中的處理常式會StackPanel StackPanel透過其由設定的Name實例buttonContainer參考來參考。Then, a handler on a Button within that StackPanel references the StackPanel through its instance reference buttonContainer as set by Name.

<StackPanel Name="buttonContainer">
  <Button Click="RemoveThis">Click to remove this button</Button>
</StackPanel>
void RemoveThis(object sender, RoutedEventArgs e)
{
    FrameworkElement fe = e.Source as FrameworkElement;
    if (buttonContainer.Children.Contains(fe))
    {
        buttonContainer.Children.Remove(fe);
    }
}
 Private Sub RemoveThis(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
     Dim fe As FrameworkElement = e.Source
     If (buttonContainer.Children.Contains(fe)) Then
         buttonContainer.Children.Remove(fe)
     End If
End Sub

就如同變數一樣,執行個體的 XAML 名稱是由範圍的概念所控制,所以可以強制名稱在可預測的部分範圍內是唯一的。Just like a variable, the XAML name for an instance is governed by a concept of scope, so that names can be enforced to be unique within a certain scope that is predictable. 定義頁面的主要標記,表示一個唯一的 XAML 名稱範圍,而 XAML 名稱範圍的界限則是該頁面的根元素。The primary markup that defines a page denotes one unique XAML namescope, with the XAML namescope boundary being the root element of that page. 然而,其他的標記來源可以於執行階段與頁面互動,例如樣式或樣式內的範本,而這類標記來源通常具有自己的 XAML 名稱範圍,其名稱範圍並不一定與頁面的 XAML 名稱範圍有所連接。However, other markup sources can interact with a page at run time, such as styles or templates within styles, and such markup sources often have their own XAML namescopes that do not necessarily connect with the XAML namescope of the page. 如需x:Name和 XAML 名稱範圍的詳細資訊Name, 請參閱、 x:Name指示詞或WPF XAML 名稱範圍For more information on x:Name and XAML namescopes, see Name, x:Name Directive, or WPF XAML Namescopes.

附加屬性和附加事件Attached properties and attached events

XAML 指定了一個語言功能,可讓某些屬性 (Property) 或事件在任何元素上指定,不論在所要設定的元素型別定義中有沒有該屬性或事件。XAML specifies a language feature that enables certain properties or events to be specified on any element, regardless of whether the property or event exists in the type's definitions for the element it is being set on. 這個功能的屬性版本稱為附加屬性,事件版本則稱為附加事件。The properties version of this feature is called an attached property, the events version is called an attached event. 在概念上來說,您可以將附加屬性和附加事件,想像成是可以在任何 XAML 元素/物件執行個體上設定的全域成員。Conceptually, you can think of attached properties and attached events as global members that can be set on any XAML element/object instance. 不過,該元素/類別或整個基礎結構必須支援附加值的支援屬性存放區。However, that element/class or a larger infrastructure must support a backing property store for the attached values.

XAML 中的附加屬性 (Property) 通常是透過屬性 (Attribute) 語法使用。Attached properties in XAML are typically used through attribute syntax. 在屬性 (Attribute) 語法中,您可以使用型式 ownerType.propertyName 指定附加屬性 (Property)。In attribute syntax, you specify an attached property in the form ownerType.propertyName.

這有點像屬性元素的使用方式,不過這裡所指定的 ownerType,一定不能是設定附加屬性之物件元素的型別。Superficially, this resembles a property element usage, but in this case the ownerType you specify is always a different type than the object element where the attached property is being set. ownerType 這個型別所提供的存取子方法,是 XAML 處理器在取得或設定附加屬性值時所需的項目。ownerType is the type that provides the accessor methods that are required by a XAML processor in order to get or set the attached property value.

最常見的附加屬性案例,是啟用子元素回報屬性值給父元素。The most common scenario for attached properties is to enable child elements to report a property value to their parent element.

下列範例說明DockPanel.Dock附加屬性。The following example illustrates the DockPanel.Dock attached property. 類別會定義的DockPanel.Dock存取子, 因此擁有附加屬性。 DockPanelThe DockPanel class defines the accessors for DockPanel.Dock and therefore owns the attached property. 類別也包含會逐一查看其子專案的邏輯, 並會特別檢查每個元素的DockPanel.Dock設定值。 DockPanelThe DockPanel class also includes logic that iterates its child elements and specifically checks each element for a set value of DockPanel.Dock. 若有找到值,就會在配置期間使用該值來放置子元素。If a value is found, that value is used during layout to position the child elements. 使用附加屬性和此定位功能實際上是DockPanel類別的激發案例。 DockPanel.DockUse of the DockPanel.Dock attached property and this positioning capability is in fact the motivating scenario for the DockPanel class.

<DockPanel>
  <Button DockPanel.Dock="Left" Width="100" Height="20">I am on the left</Button>
  <Button DockPanel.Dock="Right" Width="100" Height="20">I am on the right</Button>
</DockPanel>

WPFWPF 中,大多數或所有的附加屬性也會以相依性屬性的方式實作。In WPFWPF, most or all the attached properties are also implemented as dependency properties. 如需詳細資訊,請參閱附加屬性概觀For details, see Attached Properties Overview.

附加事件使用類似的屬性 (Attribute) 語法 ownerType.eventName 型式。Attached events use a similar ownerType.eventName form of attribute syntax. 就像非附加事件一樣,XAML 中附加事件的屬性 (Attribute) 值會指定在元素上處理事件時叫用的處理常式方法名稱。Just like the non-attached events, the attribute value for an attached event in XAML specifies the name of the handler method that is invoked when the event is handled on the element. WPF XAML 中的附加事件用法較不常見。Attached event usages in WPF XAML are less common. 如需詳細資訊,請參閱 附加事件概觀For more information, see Attached Events Overview.

基底類型和 XAMLBase types and XAML

除了 XAML 的標記元素之外, 基礎 WPF XAML 及其 XAML 命名空間也是對應至 CLR 物件的類型集合。Underlying WPF XAML and its XAML namespace is a collection of types that correspond to CLR objects in addition to markup elements for XAML. 然而,並不是所有的類別都可以對應到元素。However, not all classes can be mapped to elements. 抽象類別 (例如ButtonBase) 和特定非抽象基類會用於 CLR 物件模型中的繼承。Abstract classes, such as ButtonBase, and certain nonabstract base classes are used for inheritance in the CLR objects model. 基底類別 (包含抽象類別) 對於 XAML 開發而言仍然很重要,因為每個具象的 XAML 元素會繼承階層架構中某些基底類別的成員。Base classes, including abstract ones, are still important to XAML development because each of the concrete XAML elements inherits members from some base class in its hierarchy. 通常這些成員會包含可以設定為元素屬性 (Attribute) 的屬性 (Property),或是包含可以處理的事件。Often these members include properties that can be set as attributes on the element, or events that can be handled. FrameworkElement是 WPF 架構層UIUI級的WPFWPF實體基類。FrameworkElement is the concrete base UIUI class of WPFWPF at the WPF framework level. 在設計UIUI時, 您將使用各種圖形、面板、裝飾專案或控制項類別, 這些都是FrameworkElement衍生自。When designing UIUI, you will use various shape, panel, decorator, or control classes, which all derive from FrameworkElement. 相關的基類FrameworkContentElement, 支援適用于流程版面配置呈現的檔導向元素, 並使用故意鏡像中FrameworkElementapi 的 api。A related base class, FrameworkContentElement, supports document-oriented elements that work well for a flow layout presentation, using APIs that deliberately mirror the APIs in FrameworkElement. 元素層級和 CLR 物件模型的屬性組合提供了一組可在大部分具象 XAML 專案上設定的通用屬性, 而不論特定 XAML 專案及其基礎類型為何。The combination of attributes at the element level and a CLR object model provides you with a set of common properties that are settable on most concrete XAML elements, regardless of the specific XAML element and its underlying type.

XAML 安全性XAML security

XAML 是直接表示物件執行個體化和執行的標記語言。XAML is a markup language that directly represents object instantiation and execution. 因此,XAML 中建立的元素在與系統資源互動方面 (例如網路存取、檔案系統 IO),跟對等的產生程式碼具有一樣的能力。Therefore, elements created in XAML have the same ability to interact with system resources (network access, file system IO, for example) as the equivalent generated code does.

WPFWPF支援 .NET Framework 4 安全性架構代碼啟用安全性 (CAS)。supports the .NET Framework 4 security framework Code Access Security (CAS). 這表示在網際網路區域中執行的 WPFWPF 內容的執行權限會降低。This means that WPFWPF content running in the internet zone has reduced execution permissions. 「鬆散的 XAML」(於載入時間由 XAML 檢視器解譯的未編譯 XAML 的頁面) 和 XAML 瀏覽器應用程式 (XBAP)XAML browser application (XBAP) 通常是在這個網際網路區域中執行,並具有相同的權限設定。"Loose XAML" (pages of noncompiled XAML interpreted at load time by a XAML viewer) and XAML 瀏覽器應用程式 (XBAP)XAML browser application (XBAP) are usually run in this internet zone and use the same permission set. 然而,完全信任應用程式中載入的 XAML,具有與裝載應用程式相同的系統資源存取權限。However, XAML loaded in to a fully trusted application has the same access to the system resources as the hosting application does. 如需詳細資訊,請參閱 WPF 部分信任安全性For more information, see WPF Partial Trust Security.

從程式碼載入 XAMLLoading XAML from code

XAML 可以用來定義所有 UI,但有時候也比較適合在 XAML 中定義僅一部分的 UI。XAML can be used to define all of the UI, but it is sometimes also appropriate to define just a piece of the UI in XAML. 這些功能可以用於啟用部分自訂、資訊的區域儲存區、使用 XAML 提供商務物件或是各種可能的案例。This capability could be used to enable partial customization, local storage of information, using XAML to provide a business object, or a variety of possible scenarios. 這些案例的關鍵在於XamlReader類別和其Load方法。The key to these scenarios is the XamlReader class and its Load method. 輸入是 XAML 檔案,而輸出則是代表所有物件執行階段樹狀結構並由該標記建立的物件。The input is a XAML file, and the output is an object that represents all of the run-time tree of objects that was created from that markup. 接著,您可以將物件插入為應用程式中已經存在的其他物件的屬性。You then can insert the object to be a property of another object that already exists in the application. 只要在具有最後顯示能力且會通知執行引擎有新內容加入到應用程式的內容模型中,該屬性是適當的屬性,那麼藉由載入 XAML 就可以十分輕鬆地修改執行中應用程式的內容。So long as the property is an appropriate property in the content model that has eventual display capabilities and that will notify the execution engine that new content has been added into the application, you can modify a running application's contents very easily by loading in XAML. 請注意,這種能力通常只能在完全信任應用程式中使用,因為在應用程式執行時載入檔案會有很顯著的安全性影響。Note that this capability is generally only available in full-trust applications, because of the obvious security implications of loading files into applications as they run.

後續步驟What's next

本主題提供適用於 WPF 的 XAML 語法概念和用語基本簡介。This topic provides a basic introduction to XAML syntax concepts and terminology as it applies to WPF. 如需這裡使用的詞彙的詳細資訊,請參閱 XAML 語法詳細資料For more information about the terms used here, see XAML Syntax In Detail.

如果您尚未這麼做, 請嘗試教學課程主題逐步解說:我的第一個 WPF桌面應用程式。If you have not already done this, try the exercises in the tutorial topic Walkthrough: My first WPF desktop application. 當您建立教學課程中所涵蓋以標記為重點的應用程式時,練習可以幫助您強化本主題說明的許多概念。When you create the markup-centric application described by the tutorial, the exercise will help reinforce many of the concepts described in this topic.

WPFWPF會使用以Application類別為基礎的特定應用程式模型。uses a particular application model that is based on the Application class. 如需詳細資訊,請參閱 應用程式管理概觀For details, see Application Management Overview.

關於如何從命令列和使用 Microsoft Visual StudioMicrosoft Visual Studio 建置 XAML 內含的應用程式,建置 WPF 應用程式 將提供您更為詳細的資訊。Building a WPF Application gives you more details about how to build XAML inclusive applications from the command line and with Microsoft Visual StudioMicrosoft Visual Studio.

相依性屬性概觀 提供您有關 WPFWPF 中多樣化屬性的詳細資訊,並介紹相依性屬性的概念。Dependency Properties Overview gives more information about the versatility of properties in WPFWPF, and introduces the concept of dependency properties.

另請參閱See also