XAML 概述XAML overview

本文介绍了 Windows 运行时应用开发人员群体的 XAML 语言和 XAML 概念,并介绍了在 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 (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 语言支持在开发过程中的不同工具和角色之间交换源,例如在设计工具和交互式开发环境(IDE)之间交换 XAML 源,或在主要开发人员和本地化之间交换 XAML 源商.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 用作交换格式,可以分开或整合设计人员角色和开发人员角色,并且设计人员和开发人员可以在开发应用期间迭代。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 1.0 规范,赋予了不同的和更完整的含义,但在 XML 中仍有效。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

无论是在 XAML 文本编辑器中,还是在更为图形化的 XAML 设计界面中,Microsoft Visual Studio 都可以帮助你生成有效的 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 通过提供自动完成提示来鼓励有效的 XAML 语法,其中显示了 Microsoft IntelliSense 列表和下拉列表中的建议,并在 "工具箱" 窗口中显示了 UI 元素库或其他技术。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 运行时应用项目,此默认命名空间包含用于 UI 定义的所有 Windows 运行时的内置 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.

以下代码片段显示了模板为应用程序的初始页面创建的 @no__t 0 根(仅显示开始标记并简化)。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 标记扩展的参数,你可以在以后使用此密钥在应用 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. 默认 Windows 运行时激活模式下 Window.ContentWindow.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 运行时应用的一个组件时发生的实际情况。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的详细信息,请参阅 [Quickstart:转换 UI 资源 @ no__t。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. 例如,你可能需要一个对象,该对象表示要在 ObjectAnimationUsingKeyFrames storyboarded 可视状态中使用的true布尔值。For 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 为: @no__t 为-2,代表元素用法为: <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

你常常会看到定义前缀“d”(设计器命名空间)和“mc”(用于实现标记兼容性)的 XAML 文件。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

标记扩展是一个 XAML 语言概念,常常用在 Windows 运行时 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. @No__t-0 用法的参数用于标识 @no__t 中的键控资源的密钥(名称)。The 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 模板中,因为其中的大部分模板专门用于用户在应用运行时切换主题的兼容性。{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.

例如,以下语法用于引用 @no__t 中的可重用 ResourceDictionary<Button Style="{StaticResource SearchButtonStyle}"/>For example, here's the syntax for referencing a reusable Style from a ResourceDictionary: <Button Style="{StaticResource SearchButtonStyle}"/>. @No__t 为一个引用类型,而不是简单值,因此,如果没有 @no__t 用法,则需要一个 @no__t 2 属性元素,并在其中 @no__t 3 个定义以设置 @no__t 属性。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 示例使用特性语法来设置 @no__t @no__t 的值。To illustrate, the next XAML example sets the value of the FrameworkElement.Style property of a Border by using attribute syntax. @No__t-0 属性采用 @no__t 1 类的实例,默认情况下,无法使用特性语法字符串创建引用类型。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. 但在本例中,该属性引用一个特定的标记扩展 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.

EventsEvents

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. @No__t 0 类支持名为 @no__t 的事件。The 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>

当你进行编译时,编译器现在预期在代码隐藏文件中将有一个已定义的名为 showUpdatesButton_Click 的方法,位于 XAML 页的 x:Class 值中声明的命名空间中。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. 此外,该方法必须满足 @no__t 0 事件的委托协定。Also, 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 中如何工作以及它们与编程和应用程序模型之间的关系的详细信息,请参阅事件和路由事件概述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,有两个代码隐藏文件:一个是标头(.h),另一个是实现(.xaml)。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 声明为带有 @no__t 的根的离散 XAML 文件。When 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 使用的 XAML-for-UI 词汇表具有大量重复内容,与 WPF 所使用的词汇表的重复内容稍微少一些。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 为最初为也使用 XAML 的早期技术定义的 UI 提供了一种有效的迁移路径。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 文件时保持该文件的声明和用途的有效性。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 中经常使用相同的颜色画笔,请将 @no__t 0 定义为资源,而不是每次使用命名颜色作为特性值。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. 这对设计应用时的 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).
  • 使用诸如 @no__t 的容器,而不是特意 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.

调试 XAMLDebug 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 声明作为根视觉对象加载的应用程序的第一“页”时,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.

通常在 IDE(例如 Visual Studio 及其某一个 XAML 设计图面)中编辑 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.

一旦应用真正运行,如果任何 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 运行时应用的异常处理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 代码的应用不会获得特定的system.windows.markup.xamlparseexceptionApps that use C++/CX for code don't get the specific XamlParseException. 但是该异常与 XamlParseException 一样,包含的消息可阐明错误源与 XAML 相关,并且在 XAML 文件中包括上下文信息(例如行数)。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 运行时应用的详细信息,请参阅启动调试会话Fore more info on debugging a Windows Runtime app, see Start a debug session.