XAML 概觀XAML overview

本文介紹 XAML 語言和 XAML 概念給 Windows 執行階段的應用程式開發人員物件,並說明在 XAML 中宣告物件和設定屬性的不同方法,因為它是用來建立 Windows 執行階段應用程式。This article introduces the XAML language and XAML concepts to the Windows Runtime app developer audience, and describes the different ways to declare objects and set attributes in XAML as it is used for creating a Windows Runtime app.

什麼是 XAML?What is XAML?

Extensible Application Markup Language (XAML) 是一種宣告式語言。Extensible Application Markup Language (XAML) is a declarative language. 具體而言,XAML 可以初始化物件,並使用語言結構來設定物件的屬性,此語言結構會顯示多個物件之間的階層式關聯性,以及支援類型延伸的支援型別慣例。Specifically, XAML can initialize objects and set properties of objects using a language structure that shows hierarchical relationships between multiple objects and a backing type convention that supports extension of types. 您可以利用宣告式 XAML 標記建立視覺上可以看到的 UI 元素。You can create visible UI elements in the declarative XAML markup. 您可以接著關聯可以回應事件的每個 XAML 檔案的個別程式碼後置檔案,然後操縱您原先在 XAML 中宣告的物件。You can then associate a separate code-behind file for each XAML file that can respond to events and manipulate the objects that you originally declare in XAML.

XAML 語言支援在開發程式中的不同工具和角色之間交換來源,例如在設計工具和互動式開發環境之間交換 XAML 來源 (IDE) ,或在主要開發人員和當地語系化開發人員之間進行交換。The XAML language supports interchange of sources between different tools and roles in the development process, such as exchanging XAML sources between design tools and an interactive development environment (IDE) or between primary developers and localization developers. 使用 XAML 做為交換格式時,設計師角色和開發人員角色可以各自保持獨立或合併在一起,而設計師和開發人員在 app 製作期間可以重複。By using XAML as the interchange format, designer roles and developer roles can be kept separate or brought together, and designers and developers can iterate during the production of an app.

當您看見它們成為您 Windows 執行階段應用程式專案的一部分時,XAML 檔案是副檔名為 .xaml 的 XML 檔案。When you see them as part of your Windows Runtime app projects, XAML files are XML files with the .xaml file name extension.

基本 XAML 語法Basic XAML syntax

XAML 具備以 XML 為依據的基本語法。XAML has a basic syntax that builds on XML. 根據定義,有效的 XAML 也必須是有效的 XML。By definition, valid XAML must also be valid XML. 但是 XAML 也有語法概念,這些概念會指派不同且更完整的意義,但在 XML 中,每個 XML 1.0 規格仍有效。But XAML also has syntax concepts that are assigned a different and more complete meaning while still being valid in XML per the XML 1.0 specification. 例如,XAML 支援「屬性元素語法」**,其中的屬性值可以在元素內 (而不是當成屬性中的字串值或內容) 來設定。For example, XAML supports property element syntax, where property values can be set within elements rather than as string values in attributes or as content. 如果是一般 XML,XAML 屬性元素就是其名稱內有一個點的元素,如此一來,它對純 XML 就是有效的,但不會有相同的意義。To regular XML, a XAML property element is an element with a dot in its name, so it's valid to plain XML but doesn't have the same meaning.

XAML 和 Visual StudioXAML and Visual Studio

Microsoft Visual Studio 可以在 XAML 文字編輯器與更多圖形導向的 XAML 設計介面中,協助您產生有效的 XAML 語法。Microsoft Visual Studio helps you to produce valid XAML syntax, both in the XAML text editor and in the more graphically oriented XAML design surface. 當您使用 Visual Studio 為應用程式撰寫 XAML 時,請不要擔心每次擊鍵的語法太多。When you write XAML for your app using Visual Studio, don't worry too much about the syntax with each keystroke. IDE 會提供自動完成提示,並在 [ 工具箱 ] 視窗中顯示 UI 元素程式庫或其他技術,以鼓勵有效的 XAML 語法。The IDE encourages valid XAML syntax by providing autocompletion hints, showing suggestions in Microsoft IntelliSense lists and dropdowns, showing UI element libraries in the Toolbox window, or other techniques. 如果這是您第一次使用 XAML 的經驗,瞭解語法規則,以及在參考或其他主題中描述 XAML 語法時,有時會用來描述限制或選擇的術語,可能仍很有用。If this is your first experience with XAML, it might still be useful to know the syntax rules and particularly the terminology that is sometimes used to describe the restrictions or choices when describing XAML syntax in reference or other topics. XAML 語法的細微點涵蓋在 xaml 語法指南的個別主題中。The fine points of XAML syntax are covered in a separate topic, XAML syntax guide.

XAML 命名空間XAML namespaces

在進行一般程式設計時,命名空間是一個組織的概念,可判斷如何解譯用於程式設計實體的識別碼。In general programming, a namespace is an organizing concept that determines how identifiers for programming entities are interpreted. 透過使用命名空間,程式設計架構就可以區分使用者宣告的識別碼與架構宣告的識別碼、透過命名空間的限定性條件使識別碼意義清楚、強制執行範圍名稱的規則等等。By using namespaces, a programming framework can separate user-declared identifiers from framework-declared identifiers, disambiguate identifiers through namespace qualifications, enforce rules for scoping names, and so on. XAML 有自己的 XAML 命名空間概念,可達成 XAML 語言的這個目的。XAML has its own XAML namespace concept that serves this purpose for the XAML language. 這裡是 XAML 套用和延伸 XML 語言命名空間概念的方式:Here's how XAML applies and extends the XML language namespace concepts:

  • XAML 會使用保留的 XML 屬性 xmlns 來進行命名空間宣告。XAML uses the reserved XML attribute xmlns for namespace declarations. 這個屬性值通常是一個統一資源識別元 (URI),它是繼承自 XML 的慣例。The value of the attribute is typically a Uniform Resource Identifier (URI), which is a convention inherited from XML.
  • XAML 在宣告中使用前置詞來宣告非預設命名空間,並在元素和屬性中使用前置詞來參考該命名空間。XAML uses prefixes in declarations to declare non-default namespaces, and prefix usages in elements and attributes reference that namespace.
  • XAML 具備預設命名空間的概念,這是在用法或宣告中沒有任何前置詞存在時使用的命名空間。XAML has a concept of a default namespace, which is the namespace used when no prefix exists in a usage or declaration. 預設的命名空間可針對每個 XAML 程式設計架構,以不同方式來定義。The default namespace can be defined differently for each XAML programming framework.
  • XAML 檔案中的命名空間定義是從父元素繼承或建構到子元素。Namespace definitions inherit in a XAML file or construct, from parent element to child element. 例如,如果您在 XAML 檔案的根項目中定義命名空間,該檔案內的所有元素都會繼承該命名空間定義。For example, if you define a namespace in the root element of a XAML file, all elements within that file inherit that namespace definition. 如果進一步深入頁面的元素會重新定義命名空間,則該元素的子系會繼承新定義。If an element further into the page redefines the namespace, that element's descendants inherit the new definition.
  • 元素的屬性則是繼承元素的命名空間。Attributes of an element inherit the element's namespaces. 很少會在 XAML 屬性上看到前置詞。It's fairly uncommon to see prefixes on XAML attributes.

XAML 檔案幾乎永遠在它的根元素中宣告預設的 XAML 命名空間。A XAML file almost always declares a default XAML namespace in its root element. 預設 XAML 命名空間定義您可以宣告但不必使用前置詞來限定的元素。The default XAML namespace defines which elements you can declare without qualifying them by a prefix. 對於典型的 Windows 執行階段 app 專案,這個預設命名空間包含適用於 Windows 執行階段且可用於 UI 定義的所有內建 XAML 詞彙:預設控制項、文字元素、XAML 圖形和動畫、資料繫結與樣式支援類型等。For typical Windows Runtime app projects, this default namespace contains all the built-in XAML vocabulary for the Windows Runtime that's used for UI definitions: the default controls, text elements, XAML graphics and animations, databinding and styling support types, and so on. 您針對 Windows 執行階段應用程式所撰寫的多數 XAML 從而能在參考常見的 UI 元素時,避免使用 XAML 命名空間和前置詞。Most of the XAML you'll write for Windows Runtime apps will thus be able to avoid using XAML namespaces and prefixes when referring to common UI elements.

以下程式碼片段顯示 Page 應用程式初始頁面的範本建立的根目錄 (僅顯示開頭標記,以及簡化的) 。Here's a snippet that shows a template-created Page root of the initial page for an app (showing the opening tag only, and simplified). 它宣告預設的命名空間,以及 x 命名空間 (我們將在下段加以說明)。It declares the default namespace and also the x namespace (which we'll explain next).

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

XAML 語言 XAML 命名空間The XAML-language XAML namespace

有一個幾乎會在每個 Windows 執行階段 XAML 檔案中宣告的特定 XAML 命名空間,就是 XAML 語言命名空間。One particular XAML namespace that is declared in nearly every Windows Runtime XAML file is the XAML-language namespace. 這個命名空間包含 XAML 語言規格所定義的元素和概念。This namespace includes elements and concepts that are defined by the XAML language specification. 依照慣例,XAML 語言 XAML 命名空間會對應至前置詞 "x"。By convention, the XAML-language XAML namespace is mapped to the prefix "x". Windows 執行階段應用程式專案的預設專案與檔案範本,永遠會將預設的 XAML 命名空間 (無前置詞,只有 xmlns=) 與 XAML 語言 XAML 命名空間 (前置詞 "x") 定義為根元素的一部分。The default project and file templates for Windows Runtime app projects always define both the default XAML namespace (no prefix, just xmlns=) and the XAML-language XAML namespace (prefix "x") as part of the root element.

"x" 前置詞/XAML 語言 XAML 命名空間包含數個您經常用在 XAML 中的程式設計建構。The "x" prefix/XAML-language XAML namespace contains several programming constructs that you use often in your XAML. 以下是最常用的建構:Here are the most common ones:

詞彙Term 描述Description
x:Keyx:Key 為 XAML 中的每個資源設定唯一的使用者定義索引鍵 ResourceDictionarySets a unique user-defined key for each resource in a XAML ResourceDictionary. 索引鍵的權杖字串是 StaticResource 標記延伸的引數,而您稍後可以使用這個索引鍵,從位於 app XAML 任一處的其他 XAML 用法中抓取 XAML 資源。The key's token string is the argument for the StaticResource markup extension, and you use this key later to retrieve the XAML resource from another XAML usage elsewhere in your app's XAML.
x:Classx:Class 指定類別的程式碼命名空間和程式碼類別名稱,該類別提供 XAML 頁面的程式碼後置。Specifies the code namespace and code class name for the class that provides code-behind for a XAML page. 這會在您建置應用程式時,為組建動作所建立或加入的類別命名。This names the class that is created or joined by the build actions when you build your app. 這些組建動作支援 XAML 標記編譯器,並且可以在編譯應用程式時組合您的標記和程式碼後置。These build actions support the XAML markup compiler and combine your markup and code-behind when the app is compiled. 您必須擁有這類類別,才能支援 XAML 頁面的程式碼後置。You must have such a class to support code-behind for a XAML page. Window.Content 在預設的 Windows 執行階段啟用模型中。Window.Content in the default Windows Runtime activation model.
x:Namex:Name 為處理完 XAML 中定義的物件元素後而存在執行階段程式碼中的執行個體,指定執行階段物件名稱。Specifies a run-time object name for the instance that exists in run-time code after an object element defined in XAML is processed. 您可以將在 XAML 中設定 x:Name 想像成在程式碼中宣告具名變數。You can think of setting x:Name in XAML as being like declaring a named variable in code. 之後您就會了解,當您的 XAML 載入為 Windows 執行階段 app 的元件時所發生的狀況。As you'll learn later, that's exactly what happens when your XAML is loaded as a component of a Windows Runtime app.
注意 Name 是架構中的類似屬性,但並非所有元素都支援它。Note Name is a similar property in the framework, but not all elements support it. 當該元素類型不支援FrameworkElement.Name時,請使用x:Name進行元素識別。Use x:Name for element identification whenever FrameworkElement.Name is not supported on that element type.
x:Uidx:Uid 識別應該為某些屬性值使用當地語系化資源的元素。Identifies elements that should use localized resources for some of their property values. 如需如何使用 x:Uid 的詳細資訊,請參閱快速入門:翻譯 UI 資源For more info on how to use x:Uid, see Quickstart: Translating UI resources.
XAML 內建資料類型 (部分機器翻譯)XAML intrinsic data types 這些類型可以針對屬性或資源要求的簡單值類型指定值。These types can specify values for simple value-types when that's required for an attribute or resource. 這些內建類型會對應到通常是針對每種程式設計語言內建定義所定義的簡單值類型。These intrinsic types correspond to the simple value types that are typically defined as part of each programming language's intrinsic definitions. 例如,您可能需要物件,代表要在 storyboarded 視覺狀態中使用的 true 布林值 ObjectAnimationUsingKeyFramesFor example, you might need an object representing a true Boolean value to use in an ObjectAnimationUsingKeyFrames storyboarded visual state. 對於 XAML 中的該值,您會使用 x:Boolean 內建類型作為 object 元素,如下所示: <x:Boolean>True</x:Boolean>For that value in XAML, you'd use the x:Boolean intrinsic type as the object element, like this: <x:Boolean>True</x:Boolean>

XAML 語言 XAML 命名空間中的其他程式設計建構雖然存在,但比較少見。Other programming constructs in the XAML-language XAML namespace exist but are not as common.

將自訂類型對應到 XAML 命名空間Mapping custom types to XAML namespaces

就語言方面來說,XAML 的一個最重要概念就是能夠輕易地擴充適用於 Windows 執行階段應用程式的 XAML 詞彙。One of the most powerful aspects of XAML as a language is that it's easy to extend the XAML vocabulary for your Windows Runtime apps. 您可以在應用程式的程式設計語言中定義自己的自訂類型,然後在 XAML 標記中參考您的自訂類型。You can define your own custom types in your app's programming language and then reference your custom types in XAML markup. 透過自訂類型進行擴充的支援,基本上是內建於 XAML 語言的運作方式。Support for extension through custom types is fundamentally built-in to how the XAML language works. 架構或應用程式開發人員會負責建立 XAML 參考的支援物件。Frameworks or app developers are responsible for creating the backing objects that XAML references. 架構和應用程式開發人員都不會以其詞彙中的物件所代表或超過基本 XAML 語法規則的規格來系結。Neither frameworks nor the app developer are bound by specifications of what the objects in their vocabularies represent or do beyond the basic XAML syntax rules. (XAML 語言 XAML 命名空間類型應該執行的某些預期,但 Windows 執行階段會提供所有必要的支援。 ) (There are some expectations of what the XAML-language XAML namespace types should do, but the Windows Runtime provides all the necessary support.)

如果您針對 Windows 執行階段核心程式庫和中繼資料以外的程式庫隨附的類型使用 XAML,就必須宣告並對應含有前置詞的 XAML 命名空間。If you use XAML for types that come from libraries other than the Windows Runtime core libraries and metadata, you must declare and map a XAML namespace with a prefix. 請在元素用法中使用該前置詞,以參考您的程式庫中已定義的類型。Use that prefix in element usages to reference the types that were defined in your library. 您通常會在根元素以及其他 XAML 命名空間定義中,將前置詞對應宣告為 xmlns 屬性。You declare prefix mappings as xmlns attributes, typically in a root element along with the other XAML namespace definitions.

若要建立您自己的命名空間定義來參考自訂類型,首先要指定關鍵字 xmlns:,接著是您想要的前置詞。To make your own namespace definition that references custom types, you first specify the keyword xmlns:, then the prefix you want. 該屬性的值必須包含關鍵字 using: 做為值的第一個部分。The value of that attribute must contain the keyword using: as the first part of the value. 此值的其餘部分為字串語彙基元,依名稱參考特定程式碼支援命名空間 (其中包含您自訂的類型)。The remainder of the value is a string token that references the specific code-backing namespace that contains your custom types, by name.

前置詞定義了標記語彙基元,這個標記語彙基元是用來參考該 XAML 檔案中標記剩餘部分的那個 XAML 命名空間。The prefix defines the markup token that is used to refer to that XAML namespace in the remainder of the markup in that XAML file. 冒號字元 (:) 是放在前置詞以及 XAML 命名空間內要參考的實體之間。A colon character (:) goes between the prefix and the entity to be referenced within the XAML namespace.

例如,將前置詞對應 myTypes 至命名空間的屬性語法 myCompany.myTypes 為: xmlns:myTypes="using:myCompany.myTypes" ,且代表性元素使用方式為: <myTypes:CustomButton/>For example, the attribute syntax to map a prefix myTypes to the namespace myCompany.myTypes is: xmlns:myTypes="using:myCompany.myTypes", and a representative element usage is: <myTypes:CustomButton/>

如需針對自訂類型對應 XAML 命名空間的詳細資訊,包含適用於 Visual C++ 元件延伸 (C++/CX) 的特殊考量,請參閱 XAML 命名空間與命名空間對應For more info on mapping XAML namespaces for custom types, including special considerations for Visual C++ component extensions (C++/CX), see XAML namespaces and namespace mapping.

其他 XAML 命名空間Other XAML namespaces

您經常會看到定義前置詞的 XAML 檔案 "d" (用於設計人員命名空間) 與 "mc" (用於標記相容性)。You often see XAML files that define the prefixes "d" (for designer namespace) and "mc" (for markup compatibility). 一般而言,這些是用於基礎結構支援,或在設計階段工具中啟用情節。Generally, these are for infrastructure support or to enable scenarios in a design-time tool. 如需詳細資訊,請參閱 XAML 命名空間主題的<其他 XAML 命名空間>一節For more info, see the "Other XAML namespaces" section of the XAML namespaces topic.

標記延伸Markup extensions

標記延伸是 Windows 執行階段 XAML 實作中經常用到的 XAML 語言概念。Markup extensions are a XAML language concept that is often used in the Windows Runtime XAML implementation. 標記延伸通常代表某種「捷徑」,可讓 XAML 檔案能夠存取某個值或行為,而不只是根據支援類型來宣告元素。Markup extensions often represent some kind of "shortcut" that enables a XAML file to access a value or behavior that isn't simply declaring elements based on backing types. 部分標記延伸若其目標為簡化語法或不同 XAML 檔案間的建構,就可以使用純字串或額外巢狀元素來設定屬性。Some markup extensions can set properties with plain strings or with additionally nested elements, with the goal of streamlining the syntax or the factoring between different XAML files.

在 XAML 屬性語法中,大括號 "{" 與 "}" 表示 XAML 標記延伸用法。In XAML attribute syntax, curly braces "{" and "}" indicate a XAML markup extension usage. 這個用法會指示 XAML 處理將處理屬性值的一般處理逸出為常值字串或直接的字串可轉換值。This usage directs the XAML processing to escape from the general treatment of treating attribute values as either a literal string or a directly string-convertible value. 相反地,XAML 剖析器會呼叫可提供適用於該特定標記延伸的行為的程式碼,而該程式碼可以提供 XAML 剖析器所需的替代物件或行為結果。Instead, a XAML parser calls code that provides behavior for that particular markup extension, and that code provides an alternate object or behavior result that the XAML parser needs. 標記延伸可以有引數 (之後緊接著標記延伸名稱),而且也必須包含在大括號內。Markup extensions can have arguments, which follow the markup extension name and are also contained within the curly braces. 通常,經過評估的標記延伸會提供物件傳回值。Typically, an evaluated markup extension provides an object return value. 在剖析期間,該傳回值會插入物件樹中的位置,而此為標記延伸用法之前在來源 XAML 中的所在位置。During parsing, that return value is inserted into the position in the object tree where the markup extension usage was in the source XAML.

Windows 執行階段 XAML 支援下列標記延伸,它們定義在預設的 XAML 命名空間下,並且可被 Windows 執行階段 XAML 剖析器了解:Windows Runtime XAML supports these markup extensions that are defined under the default XAML namespace and are understood by the Windows Runtime XAML parser:

  • {x:Bind}:支援資料系結,它會在執行時間之前,藉由執行在編譯時期產生的特殊用途程式碼來延遲屬性評估。{x:Bind}: supports data binding, which defers property evaluation until run-time by executing special-purpose code, which it generates at compile-time. 這個標記延伸可支援大範圍的引數。This markup extension supports a wide range of arguments.
  • {Binding}:支援資料繫結,執行一般用途的執行階段物件檢查,將屬性評估延後到執行階段。{Binding}: supports data binding, which defers property evaluation until run-time by executing general-purpose runtime object inspection. 這個標記延伸可支援大範圍的引數。This markup extension supports a wide range of arguments.
  • {StaticResource}:支援參考中定義的資源值 ResourceDictionary{StaticResource}: supports referencing resource values that are defined in a ResourceDictionary. 這些資源可以位於不同的 XAML 檔案中,但最終必須能夠讓 XAML 剖析器在載入時找到。These resources can be in a different XAML file but must ultimately be findable by the XAML parser at load time. 使用方式的引數會 {StaticResource} 識別 (中的索引鍵) 名稱的索引鍵 ResourceDictionaryThe argument of a {StaticResource} usage identifies the key (the name) for a keyed resource in a ResourceDictionary.
  • {ThemeResource}:類似 {StaticResource},但可回應執行階段佈景主題變更。{ThemeResource}: similar to {StaticResource} but can respond to run-time theme changes. {ThemeResource} 經常出現在 Windows 執行階段預設 XAML 範本中,因為大部分的這類範本其設計目的是為了提供相容性給在 app 執行時切換佈景主題的使用者。{ThemeResource} appears quite often in the Windows Runtime default XAML templates, because most of these templates are designed for compatibility with the user switching the theme while the app is running.
  • {TemplateBinding}{Binding} 的一種特殊情況,可支援 XAML 中的控制項範本及其在執行階段的最終用法。{TemplateBinding}: a special case of {Binding} that supports control templates in XAML and their eventual usage at run time.
  • {RelativeSource}:啟用特定格式的範本繫結,其中的值是來自範本化的父系。{RelativeSource}: enables a particular form of template binding where values come from the templated parent.
  • {CustomResource}:用於進階資源查詢案例。{CustomResource}: for advanced resource lookup scenarios.

Windows 執行階段也支援 {x:Null} 標記延伸Windows Runtime also supports the {x:Null} markup extension. 您可以在 XAML 中使用這個標記延伸,將 Nullable 值設定為 nullYou use this to set Nullable values to null in XAML. 例如,您可以在的控制項範本中使用這個 CheckBox ,這會將 null 視為不定的檢查狀態, (觸發「不定」視覺狀態) 。For example you might use this in a control template for a CheckBox, which interprets null as an indeterminate check state (triggering the "Indeterminate" visual state).

標記延伸通常會從應用程式物件圖形的某個其他部分傳回現有的實例,或將值延遲到執行時間。A markup extension generally returns an existing instance from some other part of the object graph for the app or defers a value to run time. 因為您可以使用標記延伸做為屬性值,這也是典型的用法,所以您通常會看到標記延伸為參考類型屬性提供值,這些參考類型屬性可能需要其他屬性元素語法。Because you can use a markup extension as an attribute value, and that's the typical usage, you often see markup extensions providing values for reference-type properties that might have otherwise required a property element syntax.

例如,以下是參考中可重複使用的語法 Style ResourceDictionary<Button Style="{StaticResource SearchButtonStyle}"/>For example, here's the syntax for referencing a reusable Style from a ResourceDictionary: <Button Style="{StaticResource SearchButtonStyle}"/>. Style是參考型別,而不是簡單的值,因此, {StaticResource} 如果沒有使用方式,您就需要 <Button.Style> 屬性元素和 <Style> 其中的定義來設定 FrameworkElement.Style 屬性。A Style is a reference type, not a simple value, so without the {StaticResource} usage, you would've needed a <Button.Style> property element and a <Style> definition within it to set the FrameworkElement.Style property.

透過使用標記延伸,可以在 XAML 中設定的每一個屬性可能都可以在屬性語法中設定。By using markup extensions, every property that is settable in XAML is potentially settable in attribute syntax. 即使屬性不支援直接物件具現化的屬性語法,您還是可以使用屬性語法提供屬性的參考值。You can use attribute syntax to provide reference values for a property even if it doesn't otherwise support an attribute syntax for direct object instantiation. 或者,您可以啟用延遲一般需求的特定行為,讓值類型或最新建立的參考類型填入 XAML 屬性。Or you can enable specific behavior that defers the general requirement that XAML properties be filled by value types or by newly created reference types.

為了說明,下一個 XAML 範例會 FrameworkElement.Style 使用屬性語法來設定的屬性值 BorderTo illustrate, the next XAML example sets the value of the FrameworkElement.Style property of a Border by using attribute syntax. FrameworkElement.Style屬性接受類別的實例 Windows.UI.Xaml.Style ,預設無法使用屬性語法字串來建立參考型別。The FrameworkElement.Style property takes an instance of the Windows.UI.Xaml.Style class, a reference type that by default could not be created using an attribute syntax string. 但在此情況下,屬性 (Attribute) 會參考特定的標記延伸 StaticResourceBut in this case, the attribute references a particular markup extension, StaticResource. 在處理該標記延伸時,它會傳回對 Style 元素的參考,該元素是稍早在資源字典中定義為索引鍵資源的元素。When that markup extension is processed, it returns a reference to a Style element that was defined earlier as a keyed resource in a resource dictionary.

<Canvas.Resources>
  <Style TargetType="Border" x:Key="PageBackground">
    <Setter Property="BorderBrush" Value="Blue"/>
    <Setter Property="BorderThickness" Value="5"/>
  </Style>
</Canvas.Resources>
...
<Border Style="{StaticResource PageBackground}">
  ...
</Border>

您可以巢狀化標記延伸。You can nest markup extensions. 會先評估最內層的標記延伸。The innermost markup extension is evaluated first.

由於使用標記延伸,因此針對屬性中的文字 "{" 值,您需要使用特殊語法。Because of markup extensions, you need special syntax for a literal "{" value in an attribute. 如需詳細資訊,請參閱 XAML 語法指南For more info see XAML syntax guide.

事件Events

XAML 是物件與物件屬性的宣告式語言,但也包含將事件處理常式附加到標記物件的語法。XAML is a declarative language for objects and their properties, but it also includes a syntax for attaching event handlers to objects in the markup. XAML 事件語法可以接著透過 Windows 執行階段的程式撰寫模型,整合 XAML 宣告的事件。The XAML event syntax can then integrate the XAML-declared events through the Windows Runtime programming model. 您可以在處理事件的物件中指定事件名稱做為屬性名稱。You specify the name of the event as an attribute name on the object where the event is handled. 對於屬性值,您可以指定在程式碼定義的事件處理函式名稱。For the attribute value, you specify the name of an event-handler function that you define in code. XAML 處理器會使用這個名稱在載入的物件樹中建立委派表示法,並將指定的處理常式新增到內部處理常式清單。The XAML processor uses this name to create a delegate representation in the loaded object tree, and adds the specified handler to an internal handler list. 幾乎所有的 Windows 執行階段應用程式都是由標記與程式碼後置來源所定義。Nearly all Windows Runtime apps are defined by both markup and code-behind sources.

以下是一個簡單範例。Here's a simple example. Button類別支援名為的事件 ClickThe Button class supports an event named Click. 您可以為 Click 撰寫一個處理常式,執行在使用者按一下 Button 後應該叫用的程式碼。You can write a handler for Click that runs code that should be invoked after the user clicks the Button. 在 XAML 中,指定 Click 做為 Button 上的屬性。In XAML, you specify Click as an attribute on the Button. 針對屬性值提供一個字串,此字串是您處理常式的方法名稱。For the attribute value, provide a string that is the method name of your handler.

<Button Click="showUpdatesButton_Click">Show updates</Button>

當您編譯時,現在編譯器會預期在程式碼後置檔案中以及在 XAML 頁面之 x:Class 值所宣告的命名空間中,將定義一個名為 showUpdatesButton_Click 的方法。When you compile, the compiler now expects that there will be a method named showUpdatesButton_Click defined in the code-behind file, in the namespace declared in the XAML page's x:Class value. 此外,該方法必須滿足事件的委派合約 ClickAlso, that method must satisfy the delegate contract for the Click event. 例如:For example:

namespace App1
{
    public sealed partial class MainPage: Page {
        ...
        private void showUpdatesButton_Click (object sender, RoutedEventArgs e) {
            //your code
        }
    }
}
' Namespace included at project level
Public NotInheritable Class MainPage
    Inherits Page
        ...
        Private Sub showUpdatesButton_Click (sender As Object, e As RoutedEventArgs e)
            ' your code
        End Sub
    ...
End Class
namespace winrt::App1::implementation
{
    struct MainPage : MainPageT<MainPage>
    {
        ...
        void showUpdatesButton_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&);
    };
}
// .h
namespace App1
{
    public ref class MainPage sealed {
        ...
    private:
        void showUpdatesButton_Click(Object^ sender, RoutedEventArgs^ e);
    };
}

在專案中,XAML 會寫成 .xaml 檔案,您可以使用偏好的語言 (C#、Visual Basic、C++/CX) 來撰寫程式碼後置檔案。Within a project, the XAML is written as a .xaml file, and you use the language you prefer (C#, Visual Basic, C++/CX) to write a code-behind file. 當某個 XAML 檔案以標記編譯成專案建置動作的一部分時,是透過將命名空間與類別指定為 XAML 頁面根元素的 x:Class 屬性,以識別每個 XAML 頁面的 XAML 程式碼後置檔案位置。When a XAML file is markup-compiled as part of a build action for the project, the location of the XAML code-behind file for each XAML page is identified by specifying a namespace and class as the x:Class attribute of the root element of the XAML page. 如需這些機制在 XAML 中如何運作與它們和程式撰寫模型及 app 模型的關聯的相關資訊,請參閱事件與路由事件概觀For more info on how these mechanisms work in XAML and how they relate to the programming and application models, see Events and routed events overview.

注意

針對 c + +/CX,有兩個程式碼後端檔案:一個是標頭 ( .xaml) ,另一個則是實 (.. h) 。For C++/CX there are two code-behind files: one is a header (.xaml.h) and the other is implementation (.xaml.cpp). 實作會參考標頭,技術上來說,它是代表程式碼後置連線進入點的標頭。The implementation references the header, and it's technically the header that represents the entry point for the code-behind connection.

資源字典Resource dictionaries

建立 ResourceDictionary 一般工作通常是藉由將資源字典撰寫為 XAML 頁面的區域或個別的 xaml 檔案來完成。Creating a ResourceDictionary is a common task that is usually accomplished by authoring a resource dictionary as an area of a XAML page or a separate XAML file. 資源字典及其使用方式是一個大範圍的概念,不在本主題的討論範圍內。Resource dictionaries and how to use them is a larger conceptual area that is outside the scope of this topic. 如需詳細資訊,請參閱 ResourceDictionary 和 XAML 資源參考For more info see ResourceDictionary and XAML resource references.

XAML 與 XMLXAML and XML

XAML 語言基本上是以 XML 語言為基礎。The XAML language is fundamentally based on the XML language. 但 XAML 大幅擴充了 XML。But XAML extends XML significantly. 具體來說,由於它與支援類型概念的關係,因此處理結構描述概念的方式相當不同,並且會新增語言元素,像是附加的成員與標記延伸。In particular it treats the concept of schema quite differently because of its relationship to the backing type concept, and adds language elements such as attached members and markup extensions. xml:lang 在 XAML 中有效,但會影響執行階段而非剖析行為,並且通常會產生別名到架構層級屬性。xml:lang is valid in XAML, but influences runtime rather than parse behavior, and is typically aliased to a framework-level property. 如需詳細資訊,請參閱 FrameworkElement.LanguageFor more info, see FrameworkElement.Language. xml:base 在標記中有效,但剖析器會忽略它。xml:base is valid in markup but parsers ignore it. xml:space 有效,但只與 XAML 與空格主題中描述的案例有關。xml:space is valid, but is only relevant for scenarios described in the XAML and whitespace topic. encoding 屬性在 XAML 中有效。The encoding attribute is valid in XAML. 僅支援 UTF-8 與 UTF-16 編碼。Only UTF-8 and UTF-16 encodings are supported. 不支援 UTF-32 編碼。UTF-32 encoding is not supported.

XAML 中的區分大小寫功能Case sensitivity in XAML

XAML 會區分大小寫。XAML is case-sensitive. 這是 XAML 以 XML 做為基礎的另一個結果,XML 會區分大小寫。This is another consequence of XAML being based on XML, which is case-sensitive. XAML 元素的名稱與屬性會區分大小寫。The names of XAML elements and attributes are case-sensitive. 屬性值可能會區分大小寫;這取決於特定屬性的屬性值如何處理。The value of an attribute is potentially case-sensitive; this depends on how the attribute value is handled for particular properties. 例如,如果屬性值宣告列舉的某個成員名稱,轉換成員名稱字串類型以傳回列舉成員值的內建行為不會區分大小寫。For example, if the attribute value declares a member name of an enumeration, the built-in behavior that type-converts a member name string to return the enumeration member value is not case-sensitive. 相反地,Name 屬性的值與用在以 Name 屬性宣告的名稱為基礎的物件的公用程式方法,會以區分大小寫的方式來處理名稱字串。In contrast, the value of the Name property, and utility methods for working with objects based on the name that the Name property declares, treat the name string as case-sensitive.

XAML 命名範圍XAML namescopes

XAML 語言定義 XAML 命名範圍的概念。The XAML language defines a concept of a XAML namescope. XAML 命名範圍概念會影響 XAML 處理器應如何處理套用到 XAML 元素的 x:NameName 的值,尤其是需要名稱做為唯一識別碼的範圍。The XAML namescope concept influences how XAML processors should treat the value of x:Name or Name applied to XAML elements, particularly the scopes in which names should be relied upon to be unique identifiers. XAML 命名範圍在不同的主題中有更詳細的說明;請參閱 XAML 命名範圍XAML namescopes are covered in more detail in a separate topic; see XAML namescopes.

XAML 在開發程序中的角色The role of XAML in the development process

XAML 在應用程式開發程序中扮演了數個重要的角色。XAML plays several important roles in the app development process.

  • 如果您是使用 C#、Visual Basic 或 C++/CX 進行程式設計,XAML 是宣告應用程式 UI 以及該 UI 中元素的主要格式。XAML is the primary format for declaring an app's UI and elements in that UI, if you are programming using C#, Visual Basic or C++/CX. 通常您的專案至少會有一個 XAML 檔案來表示應用程式最初顯示 UI 的頁面隱喻。Typically at least one XAML file in your project represents a page metaphor in your app for the initially displayed UI. 其他的 XAML 檔案可以為瀏覽 UI 宣告其他頁面。Additional XAML files might declare additional pages for navigation UI. 其他 XAML 檔案可以宣告資源,如範本或樣式。Other XAML files can declare resources, such as templates or styles.
  • 您使用 XAML 格式來宣告套用到應用程式中控制項和 UI 的樣式和範本。You use the XAML format for declaring styles and templates applied to controls and UI for an app.
  • 為了將現有控制項範本化,或如果您定義的控制項會提供預設範本做為控制項套件的一部分,您可能會使用樣式和範本。You might use styles and templates either for templating existing controls, or if you define a control that supplies a default template as part of a control package. 當您使用它來定義樣式和範本時,相關的 XAML 通常會宣告為具有根目錄的離散 XAML 檔案 ResourceDictionaryWhen you use it to define styles and templates, the relevant XAML is often declared as a discrete XAML file with a ResourceDictionary root.
  • XAML 是設計工具支援的常見格式,可以在不同的設計工具應用程式之間建立應用程式 UI 和交換 UI 設計。XAML is the common format for designer support of creating app UI and exchanging the UI design between different designer apps. 最特別的是,應用程式的 XAML 可以在不同的 XAML 設計工具 (或工具內的設計視窗) 之間交換使用。Most notably, XAML for the app can be interchanged between different XAML design tools (or design windows within tools).
  • 有數種其他技術也可以在 XAML 中定義基本 UI。Several other technologies also define the basic UI in XAML. 和 Windows Presentation Foundation (WPF) XAML 與 Microsoft Silverlight XAML 類似,Windows 執行階段的 XAML 會使用其共用預設 XAML 命名空間的相同 URI。In relationship to Windows Presentation Foundation (WPF) XAML and Microsoft Silverlight XAML, the XAML for Windows Runtime uses the same URI for its shared default XAML namespace. Windows 執行階段的 XAML 詞彙與 Silverlight 也會使用的 UI XAML 詞彙大幅重疊,而 WPF 使用的 UI XAML 詞彙重疊程度則較低。The XAML vocabulary for Windows Runtime overlaps significantly with the XAML-for-UI vocabulary also used by Silverlight and to a slightly lesser extent by WPF. 因此,XAML 會為 UI 升級原先定義前導技術 (也使用 XAML) 的有效移轉路徑。Thus, XAML promotes an efficient migration pathway for UI originally defined for precursor technologies that also used XAML.
  • XAML 定義 UI 的視覺外觀,而關聯的程式碼後置檔案定義邏輯。XAML defines the visual appearance of a UI, and an associated code-behind file defines the logic. 您不用變更程式碼後置中的邏輯就可以調整 UI 設計。You can adjust the UI design without making changes to the logic in code-behind. XAML 簡化了設計人員與開發人員之間的工作流程。XAML simplifies the workflow between designers and developers.
  • 因為支援 XAML 語言的視覺化設計工具及設計表面的豐富性,所以 XAML 也支援早期開發階段中的快速 UI 原型設計。Because of the richness of the visual designer and design surface support for the XAML language, XAML supports rapid UI prototyping in the early development phases.

視您在開發程序中的角色而定,您不一定會與 XAML 有很多的互動。Depending on your own role in the development process, you might not interact with XAML much. 您與 XAML 檔案互動的程度也取決於您所使用的開發環境、是否使用互動式設計環境功能 (如工具箱和屬性編輯器),以及您 Windows 執行階段應用程式的範圍和用途。The degree to which you do interact with XAML files also depends on which development environment you are using, whether you use interactive design environment features such as toolboxes and property editors, and the scope and purpose of your Windows Runtime app. 儘管如此,在應用程式的開發期間,您會使用文字或 XML 編輯器在元素層級編輯 XAML 檔案。Nevertheless, it is likely that during development of the app, you will be editing a XAML file at the element level using a text or XML editor. 使用這項資訊,您可以在文字或 XML 表示法中放心編輯 XAML,並在您的 Windows 執行階段應用程式的工具、標記編譯作業或執行階段使用 XAML 時,維持該 XAML 檔案宣告的有效性。Using this info, you can confidently edit XAML in a text or XML representation and maintain the validity of that XAML file's declarations and purpose when it is consumed by tools, markup compile operations, or the run-time phase of your Windows Runtime app.

針對載入效能將您的 XAML 最佳化Optimize your XAML for load performance

以下是使用效能最佳做法定義 XAML 中 UI 元素的一些祕訣。Here are some tips for defining UI elements in XAML using best practices for performance. 這些祕訣中有許多與使用 XAML 資源相關,但是基於方便性,所以在一般 XAML 概觀這裡列出。Many of these tips relate to using XAML resources, but are listed here in the general XAML overview for convenience. 如需有關 XAML 資源的詳細資訊,請參閱 ResourceDictionary 與 XAML 資源參考For more info about XAML resources see ResourceDictionary and XAML resource references. 如需更多有關效能的提示,包含特意示範一些您應該在 XAML 中避免的不良效能做法的 XAML,請參閱最佳化您的 XAML 標記For some more tips on performance, including XAML that purposely demonstrates some of the poor performance practices that you should avoid in your XAML, see Optimize your XAML markup.

  • 如果您在 XAML 中經常使用相同的色彩筆刷,請將定義為 SolidColorBrush 資源,而不是每次都使用命名色彩做為屬性值。If you use the same color brush often in your XAML, define a SolidColorBrush as a resource rather than using a named color as an attribute value each time.
  • 如果您在多個 UI 頁面上使用相同的資源,請考慮在 Resources 每個頁面上進行定義,而不是在每個頁面上。If you use the same resource on more than one UI page, consider defining it in Resources rather than on each page. 相反地,如果只有一個頁面使用某個資源,就不要在 Application.Resources 中定義該資源,而是只針對需要使用的頁面定義。Conversely, if only one page uses a resource, don't define it in Application.Resources and instead define it only for the page that needs it. 這在設計 app 期間用來分解 XAML 非常好用,同時對於剖析 XAML 期間的效能非常有助益。This is good both for XAML factoring while designing your app and for performance during XAML parsing.
  • 針對您應用程式封裝的資源檢查未使用的資源 (具有索引鍵,但是在使用它的應用程式中並沒有 StaticResource 參考的資源)。For resources that your app packages, check for unused resources (a resource that has a key, but there's no StaticResource reference in your app that uses it). 請先從您的 XAML 中移除這些資源,然後再發行您的應用程式。Remove these from your XAML before you release your app.
  • 如果您要使用 () 提供設計資源的個別 XAML 檔案 MergedDictionaries ,請考慮批註或移除這些檔案中未使用的資源。If you're using separate XAML files that provides design resources (MergedDictionaries), consider commenting or removing unused resources from these files. 即使您在一個以上的應用程式中使用共用的 XAML 起點或是使用共用的 XAML 起點來為所有應用程式提供常見資源,每次仍是由您的應用程式封裝 XAML 資源,而且可能必須載入它們。Even if you have a shared XAML starting point that you're using in more than one app or that provides common resources for all your app, it's still your app that packages the XAML resources each time, and potentially has to load them.
  • 不要定義組合項目中不需要的 UI 元素,盡可能使用預設的控制項範本 (這些範本已經針對載入效能進行測試與驗證)。Don't define UI elements you don't need for composition, and use the default control templates whenever possible (these templates have already been tested and verified for load performance).
  • 使用容器(例如, Border 而不是刻意 overdraws 的 UI 元素)。Use containers such as Border rather than deliberate overdraws of UI elements. 基本上,請不要多次繪製同一個像素。Basically, don't draw the same pixel multiple times. 如需過度繪製及其測試方式的詳細資訊,請參閱 DebugSettings.IsOverdrawHeatMapEnabledFor more info on overdraw and how to test for it, see DebugSettings.IsOverdrawHeatMapEnabled.
  • 使用或的預設專案範本 ListViewGridView 這些範本具有特殊的 簡報者 邏輯,可解決建立大量清單專案的視覺化樹狀結構時的效能問題。Use the default items templates for ListView or GridView; these have special Presenter logic that solves performance issues when building the visual tree for large numbers of list items.

針對 XAML 進行偵錯Debug XAML

因為 XAML 是一種標記語言,所以在 Microsoft Visual Studio 內一些偵錯的典型策略就無法使用。Because XAML is a markup language, some of the typical strategies for debugging within Microsoft Visual Studio are not available. 例如,您無法在 XAML 檔案內設定中斷點。For example, there is no way to set a breakpoint within a XAML file. 不過,仍處於開發應用程式階段時,還是有其他技術可以協助您偵錯 UI 定義或其他 XAML 標記的問題。However, there are other techniques that can help you debug issues with UI definitions or other XAML markup while you're still developing your app.

當 XAML 檔案有問題的時候,最典型的結果是有些系統或您的應用程式會擲回 XAML 剖析例外狀況。When there are problems with a XAML file, the most typical result is that some system or your app will throw a XAML parse exception. 出現 XAML 剖析例外狀況時,XAML 剖析器載入的 XAML 無法建立有效的物件樹狀結構。Whenever there is a XAML parse exception, the XAML loaded by the XAML parser failed to create a valid object tree. 在有些情況下,像是 XAML 呈現載入為根 Visual 的應用程式第一個「頁面」時,XAML 剖析例外狀況是不可復原的。In some cases, such as when the XAML represents the first "page" of your application that is loaded as the root visual, the XAML parse exception is not recoverable.

XAML 通常是在 IDE 內 (如 Visual Studio) 以及它的其中一個 XAML 設計表面內進行編輯。XAML is often edited within an IDE such as Visual Studio and one of its XAML design surfaces. Visual Studio 通常可在您編輯的時候提供設計階段驗證及 XAML 來源的錯誤檢查。Visual Studio can often provide design-time validation and error checking of a XAML source as you edit it. 例如,當您輸入錯誤的屬性值時,它會立即在 XAML 文字編輯器中顯示「波浪線」,您甚至不用等 XAML 編譯傳送,就能看到 UI 定義中有錯誤。For example it might display "squiggles" in the XAML text editor as soon as you type a bad attribute value, and you won't even have to wait for a XAML compile pass to see that something's wrong with your UI definition.

一旦 app 實際執行之後,如果設計階段未偵測到任何 XAML 剖析錯誤,通用語言執行階段 (CLR) 就會將它們報告為 XamlParseExceptionOnce the app actually runs, if any XAML parse errors have gone undetected at design time, these are reported by the common language runtime (CLR) as a XamlParseException. 如需可在執行階段 XamlParseException 執行哪些動作的詳細資訊,請參閱 C# 或 Visual Basic 中 Windows 執行階段 app 的例外狀況處理For more info on what you might be able to do for a run-time XamlParseException, see Exception handling for Windows Runtime apps in C# or Visual Basic.

注意

使用 c + +/CX 進行程式碼的應用程式不會取得特定的 XamlParseExceptionApps that use C++/CX for code don't get the specific XamlParseException. 但是,例外狀況中的訊息可清楚說明錯誤來源是與 XAML 相關,而且其中包含內容資訊,例如 XAML 檔案中的行號,就像 XamlParseException 一樣。But the message in the exception clarifies that the source of the error is XAML-related, and includes context info such as line numbers in a XAML file, just like XamlParseException does.

如需有關將 Windows 執行階段應用程式進行偵錯工具的詳細資訊,請參閱 啟動 debug 會話For more info on debugging a Windows Runtime app, see Start a debug session.