Windows Phone 7-Introduction to The XAML syntax

Source: Internet
Author: User

What isXAML?

XAML is a declarative markup language. Like the. NET Framework programming model, XAML simplifies the application for. NET Framework.ProgramUi creation process. You can create visible UI elements in declarative XAML markup and then useCodeHidden Files (connected by the Division class definition and tag) Separate the UI definition from the runtime logic. XAML directly uses a set of specific backup types defined in the Assembly to indicate Object Instantiation.

The following example shows how to create a button as part of the UI. The purpose of this example is only to give you a preliminary understanding of how XAML represents common UI programming forms (it is not a complete example ).

<Stackpanel>

<Button content = "Click me"/>

</Stackpanel>

 

 

XAMLLanguageOverview

XAMLPairElephant Element

<Stackpanel>

<Button content = "Click me"/>

</Stackpanel>

This example specifies two object elements: <stackpanel> (containing content, followed by an end tag) and <button.../> (self-ending form, including several features ). Each object element stackpanel and button are mapped to a class name. These classes are defined by WPF and are part of the WPF assembly. When an object element is marked, a XAML Processing Command is created to create a new instance. Each instance is created by calling the default constructor of the basic type during analysis and loading of XAML.

FeaturesLanguageMethod (attribute)

The attributes of an object can be expressed as the characteristics of an object element. The feature syntax name is the attribute set in the feature syntax, followed by the value assignment operator (= ). The feature value is always specified as a string contained in quotation marks.

Feature syntax is the simplest and most effective syntax for property settings. It is the most intuitive syntax for developers who have used Markup languages. For example, the following tag creates a button with a red text and a blue background, and a display text specified as content.

<Button background = "blue" foreground = "red" content = "this is a button"/>

 

 

Attribute ElementLanguageMethod

For some attributes of an object element, the feature syntax is impossible, because it cannot fully express the objects or information necessary to provide the attribute value within the quotation marks and string restrictions of the feature syntax. In these cases, you can use another syntax, namely the attribute element syntax.

The syntax for starting to mark attribute elements is <type name. attribute name>. Generally, the content of the tag is an object element of the type, and the attribute uses this element as its value. After the content is specified, an end tag must be used to end the attribute element. The end tag syntax is </type name. attribute name>.

If you can use the feature syntax, it is generally more convenient to use the feature syntax and can implement a more streamlined tag, but this is usually just a style problem, not a technical limitation. The following example demonstrates the same attributes set in the previous feature syntax example, but the attribute element syntax is used for all the attributes 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>

SetLanguageMethod

The XAML language contains some optimizations to generate more readable markup. One of the optimizations is that if a specific property uses a set type, the items that declare as the child elements in the value of the property in the tag will become part of the set. In this case, the set of sub-object elements is set as the value of the set attribute.

The following example demonstrates the set syntax for setting values for the gradientstops attribute:

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

XAMLContent Attributes

XAML specifies a language function. With this function, one class can specify one of its attributes as the XAML content attribute. The child element of the object element is used to set the value of the content attribute. In other words, for content attributes only, you can omit the attribute element when setting this attribute in the XAML tag and generate a more intuitive parent/child form in the tag.

For example, border specifies the content attribute child. The system processes the following two border elements in the same way. The first element uses the content attribute syntax to omit the border. Child attribute element. The second element explicitly indicates border. Child.

<Border>

<Textbox width = "300"/>

</Border>

<! -- Explicit equivalent -->

<Border>

<Border. Child>

<Textbox width = "300"/>

</Border. Child>

</Border>

As a rule of the XAML language, the value of the XAML content attribute must be specified before or after any other attribute element of the object element. For example, the following mark cannot be compiled:

Copy

<Button> I am

<Button. Background> blue </button. Background>

Blue button </button>

For more information about this restriction of XAML content attributes, see the "XAML content attributes" section in the XAML syntax details.

Text Content

A small number of XAML elements can directly process text as their content. To implement this function, you must meet one of the following conditions:

    • Class must declare a content attribute, and the content attribute must be a type that can be assigned to a string (this type can be an object ). For example, any contentcontrol uses content as its content attribute and its type is object. In this way, the following uses the actual contentcontrol (for example, button: <button> Hello </button>.
    • A type converter must be declared as a type converter that uses text content as its initialization text. For example, <brush> blue </brush>. This is actually not common.
    • The type must be a known XAML language primitive.

Content attributes and setLanguageMethodGroupIntegration

See the following example:

<Stackpanel>

<Button> first button </button>

<Button> second button </button>

</Stackpanel>

In this example, each button is a sub-element of stackpanel. This is a simple and intuitive tag, and two tags are omitted for two different reasons.

    • OmittedStackpanel. ChildrenAttribute element:Stackpanel is derived from panel. Panel defines panel. Children as its XAML content attribute.
    • OmittedUielementcollectionPairImage element:The Panel. Children attribute adopts the type uielementcollection, which implements ilist. Element tags of a collection can be omitted Based on The XAML rules for processing sets (such as ilist. (In this case, uielementcollection cannot be instantiated because it does not expose the default constructor. This is why the elements of the uielementcollection object appear in the form of annotations .)

<Stackpanel>

<Stackpanel. Children>

<! -- <Uielementcollection> -->

<Button> first button </button>

<Button> second button </button>

<! -- </Uielementcollection> -->

</Stackpanel. Children>

</Stackpanel>

FeaturesLanguageMethod (Event)

The feature syntax can also be used for event members, not limited to attribute members. In this case, the feature name is the event name. In the WPF implementation of a XAML event, the property value is the name of the handler that delegates the event. For example, the following tag specifies a handler of the click event to the button created in the tag:

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

XAMLCase and white space in

XAML is usually case sensitive. For the purpose of parsing Backup Types, wpf xaml is case-sensitive according to the same CLR case-sensitive rules. When comparing object elements, attribute elements, and feature names by name with the basic type in the assembly, or comparing them with type members, the object elements, attribute elements, and feature names must be case-sensitive. The XAML language keywords and base elements are also case sensitive. The value is not always case sensitive. Whether the value is case sensitive depends on the type converter action associated with the property that uses the value, or the type of the property value. For example, a property of the boolean type can use True or true as the equivalent value, but only because the type conversion of the local wpf xaml analyzer that converts the string to boolean has allowed these values as the equivalent value.

The wpf xaml processor and serialization program will ignore or delete all meaningless white spaces and normalize any meaningful white spaces. This is consistent with the default blank behavior suggestions in the XAML specification. Generally, this behavior is important only when you specify a string in the XAML content attribute. In short, XAML converts spaces, linefeeds, and tabs into spaces. If they appear at either end of a continuous string, a space is retained. The complete description of XAML blank processing is not covered in this topic.

Mark ExpansionExhibition

Tag extension is a concept of XAML language. When used to provide the value of the feature syntax, braces ({And}) indicate tag extension usage. This usage indicates that the XAML processing system does not treat a feature value as a text string or a value that can be converted to a string as usual.

The most common markup extension in WPF Application Programming is binding (used for data binding expressions) and resource reference staticresource and dynamicresource. By using tag extension, you can use the feature syntax to provide a value for the property even if the property generally does not support the feature syntax. Tag extension often uses the intermediate expression type to implement some functions, such as postponing a value or referencing other objects that only exist at runtime.

For example, the following tag uses the feature syntax to set the value of the style attribute. The style attribute uses an instance of the Style Class. By default, this instance cannot be instantiated using the feature syntax string. However, in this example, the feature references a specific tag extension staticresource. When processing the tag extension, it returns a reference to a style that was previously instantiated as a key resource in the 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>

 

 

For a reference list of all XAML tag extensions specifically implemented in WPF, see wpf xaml extensions. For a reference list of tag extensions defined by system. XAML and more widely used in. Net XAML implementation, see The XAML namespace (x :) language feature. For more information about the markup extension concept, see markup extension and wpf xaml.

ClassTypeConversionTool

In this section, we mentioned that feature values must be set using strings. The basic local processing of how a string is converted to another object type or primitive value depends on the string type itself, and the local processing of some types (such as datetime or Uri. However, many WPF types or members of these types extend the basic string feature to process behavior, so you can specify instances of more complex object types as strings and features.

The thickness structure is a type example, which can be converted using the type of XAML. Thickness indicates the measurement in the nested rectangle and serves as the value of some attributes (such as margin. By setting the type converter for thickness, all attributes that use thickness can be easily specified in XAML because they can be specified as features. The following example uses the type conversion and feature syntax to provide values for margin:

<Button margin = "10, 20, 10, 30" content = "Click me"/>

 

 

The preceding feature syntax example is equivalent to the more detailed syntax example below, but in the following example, margin is set by the attribute element syntax containing the thickness object element. In addition, set the four key attributes of thickness as the features of the new instance:

<Button content = "Click me">

<Button. margin>

<Thickness left = "10" Top = "20" Right = "10" Bottom = "30"/>

</Button. margin>

</Button>

 

 

DescriptionMing

There are also a few objects that can only set attributes for this type without involving subclass through type conversion, because the type itself does not have a default constructor. An example is cursor.

For more information about how to support type conversion and Its Application in feature syntax, see typeconverters and XAML.

XAMLRoot element andXAMLName blankRoom

A XAML file can only have one root element, so that it can be a correctly formatted XML file and a valid XAML file at the same time. For a typical WPF solution, the root elements that are important in the WPF application model are used (for example, window or page is used for pages, use resourcedictionary for the external dictionary or use application for the application definition ). The following example shows the root element of a typical XAML file on the WPF page. The root element is page.

<Page

Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"

 

 

...

 

 

</Page>

 

 

The root element also contains the xmlns and xmlns: X features. These features indicate to the XAML processor which XAML namespaces contain type definitions that mark the backup types to be referenced as elements. The xmlns feature explicitly indicates the default XAML namespace. In the default XAML namespace, object elements in the tag can be specified without the prefix. For almost all examples provided in most WPF application solutions and sdk wpf, the default XAML namespace is mapped to the WPF namespace http://schemas.microsoft.com/winfx/2006/xaml/presentation. Xmlns: X indicates another XAML namespace, which maps to the XAML language namespace http://schemas.microsoft.com/winfx/2006/xaml.

The use of xmlns to define usage range and name range ing is in line with the XML 1.0 specification. The differences between the XAML name range and the XML name range are that the XAML name range also contains information about how type-supported elements of the name range during type parsing and Analysis of XAML.

Note: The xmlns feature is absolutely required only on the root element of each XAML file. The xmlns definition applies to all child elements of the root element (this behavior also complies with the XML 1.0 specification of xmlns .) At the same time, other elements below the root can have the xmlns feature, which will apply to any child element that defines the element. However, frequent or redefinition of the XAML namespace may make the XAML tag style hard to read.

The WPF implementation of its XAML processor includes the infrastructure that recognizes the WPF core assembly. It is known that the WPF Core Assembly contains a type that supports the WPF ing from WPF to the default XAML namespace. This is achieved through the configuration of the Project generation file, the WPF generation and the project system. Therefore, to reference the XAML elements from the WPF assembly, you only need to declare the default XAML namespace as the default xmlns.

X:BeforeFix

In the preceding root element example, the prefix X is used to map the XAML namespace http://schemas.microsoft.com/winfx/2006/xaml. this namespace is a specialized XAML namespace that supports the construction of The XAML language. In the entire SDK Project template, example, and documentation, the X: prefix is used to map the XAML namespace. The XAML namespace Of The XAML language contains multiple programming structures that will be frequently used in The XAML. The most common X: prefix programming structure is listed below:

    • X: Key: Set a unique key for each resource in resourcedictionary (or similar dictionary concepts in other frameworks. In all X: usage in a typical WPF Application tag, X: key may account for 90%.
    • X: Class: Specifies the CLR namespace and class name for Classes hidden by code provided to the XAML page. You must have such a class to support code hiding for each WPF programming model. Therefore, even if there is no resource, you can almost always see the mapped X :.
    • X: Name: Specifies the name of the runtime object for an instance in the runtime code after processing the object element. Generally, you will often use the equivalent property defined by WPF for X: Name. This type of property is mapped to the CLR reserve property, so it is easier for application programming. In application programming, you often use the runtime code to find the name element from the initialized XAML. The most common attribute is frameworkelement. Name. If the specified type does not support the equivalent WPF framework-level name attribute, you can still use X: Name. This happens in some animation schemes.
    • X: static: enables a reference to return a static value. This static value can only be a XAML compatible attribute.
    • X: Type: Construct a type reference based on the Type name. It is used to specify the type (for example, style. targettype) feature, but attributes often have the function of converting the local string to type. Therefore, it is optional to use the X: Type flag for extended usage.

X: the prefix/XAML namespace contains other less common programming structures. For more information, see the XAML namespace (x :) language function.

XAMLInYiBeforeFixAnd customCategoryType

For your own custom assembly or assembly other than the WPF core of presentationcore, presentationframework, and windowsbase, you can specify this Assembly as part of the custom xmlns ing. As long as the type can be correctly implemented to support your intended XAML usage, You can reference the type in the Assembly in XAML.

The following is a basic example of how a custom prefix works in a XAML tag. The prefix custom is defined in the root element tag and mapped to a specific assembly that is packaged with the application and can be used for the application. This Assembly contains the numericupdown type. The purpose of this type is to allow insertion of class inheritance at this specific point of the wpf xaml Content Model in addition to regular XAML usage. By using this prefix, an instance of the numericupdown control is declared as an object element so that the XAML analyzer can find a XAML namespace containing this type, locate the location of the backup Assembly that contains the definition of this type.

Copy

<Page

Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"

Xmlns: Custom = "CLR-namespace: numericupdowndownmcontrol; Assembly = customlibrary"

>

<Stackpanel name = "layoutroot">

<Custom: numericupdown name = "numericctrl1" width = "100" Height = "60"/>

... </Stackpanel>

</Page>

For more information about custom types in XAML, see custom classes in XAML and WPF.

For more information about how to configure the namespace of the XML namespace and the backup code in the Assembly, see The XAML namespace and namespace ing of wpf xaml.

Events andXAMLGenerationCode hidingZang

Most WPF applications include both XAML markup and code hiding. In a project, XAML is written as a. XAML file, and CLR language (such as Microsoft Visual Basic. Net or C #) is used to write code hidden files. When the XAML file is marked and compiled in the WPF programming and application model, the position of the XAML code hidden file of the XAML file is identified in the following way: X of the root element of the XAML: the class feature specifies a namespace and class.

In the example already described, you have seen several buttons, but no button has any associated logical behavior. The main application-level mechanism for adding actions to an object element is to use existing events of the element class, and write a specific handler for the event called when the event is triggered at runtime. The event name and the name of the handler to be used are specified in the tag, and the Code for implementing the handler is defined in the Code hiding.

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

 

 

 

 

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

 

 

Note that the Code hiding file uses the CLR namespace examplenamespace and declares examplepage as a Division class in the namespace. This is equivalent to the X: class feature value of examplenamespace. examplepage provided in the flag root. The WPF markup compiler will derive a class from the root element type and create a partial class for any compiled XAML file. When you provide code hiding that defines the same branch class, the code will be combined in the same namespace and class as the compiled application.

For more information about code hiding programming requirements in WPF, see Code hiding, event handlers, and Division class requirements in WPF and in XAML.

If you do not want to create a separate hidden code file, you can also inline the code into the XAML file. However, Inline code is a method that lacks diversity and has many restrictions. For more information, see Code hiding and XAML in WPF.

Routing event

A routing event is a special event function, which is the basis of WPF. Routing events allow one element to process events triggered by another element, provided that these elements are connected together through a tree relationship. When you use the XAML feature to specify event processing, you can listen to and process any element (including the element that does not list the routing event in the class member table) of the event. This is achieved by specifying the event name with the class name. For example, in the currently discussed stackpanel/button example, the parent stackpanel can specify the feature button on the stackpanel object element. click, and use the handler name as the feature value to register a handler for the click event of the child element button. For more information about how routing events work, see routing events overview.

XAMLNaming element

By default, the object instance created by processing the XAML object element in the object graph does not have a unique identifier or object reference. On the contrary, if you call a constructor in code, you will almost always use the constructor result to set a variable for the constructor instance so that it can be referenced in code later. To provide standardized access to objects created by TAG definitions, XAML defines the X: Name feature. You can set the X: Name attribute value on any object element. In code hiding, the identifier you selected is equivalent to referencing the instance variable of the constructed instance. In any aspect, naming elements work like they are object instances (this name references this instance), and code hiding can reference this naming element to process runtime interactions within the application. This connection between instances and variables is implemented by the wpf xaml markup compiler and involves more specific functions and modes. For example, initializecomponent will not be discussed in detail in this topic.

The WPF framework-level XAML element inherits the name attribute, which is equivalent to the X: Name attribute defined by XAML. Some other classes also provide Attribute-level equivalent items for X: Name (usually defined as the name attribute. Generally, if you cannot find the name attribute in the selected element/type member table, you can use X: name instead. The X: name value provides an identifier for the XAML element used at runtime through a specific subsystem or a utility method such as findname.

The following example sets name on the stackpanel element. Then, the handler on the button in the stackpanel references the stackpanel by referencing the buttoncontainer with the instance set by name.

<Stackpanel name = "buttoncontainer">

 

 

...

 

 

<Button click = "removethis"> click to remove this button </button>

</Stackpanel>

 

 

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

 

 

Just like a variable, the instance's XAML name is controlled by the range concept, so it can be forced to be unique within a predictable range. The primary tag of the defined page indicates a unique XAML name range, and the boundary of the XAML name range is the root element of the page. However, other tag sources (such as templates in a style or style) can interact with the page at runtime, which often have their own XAML name range, these name ranges are not necessarily associated with the page's XAML name range. For more information about the X: Name and XAML name ranges, see the name, X: Name command, or wpf xaml name range.

Additional attributes and additional events

XAML specifies a language function that allows you to specify certain attributes or events for any element, regardless of whether the attribute or event exists in the Type Definition of the element to be set. The attribute version of this function is called an additional attribute, and the event version is called an additional event. Conceptually, additional attributes and additional events can be considered as global members that can be set on any XAML element/object instance. However, elements/classes or larger infrastructures must support additional value-added backup property storage.

The additional attributes in XAML are usually used through the feature syntax. In the feature syntax, you can specify additional properties in the form of "owner type. property name.

On the surface, this is similar to the usage of attribute elements, but in this case, the "owner type" you specify is always a type different from the object element from which you want to set additional attributes. The "owner type" type provides the accessors required by the XAML processor to obtain or set additional attribute values.

The most common scheme to use additional attributes is to enable the child element to report attribute values to its parent element.

The following example demonstrates the dockpanel. Dock additional attributes. The dockpanel class defines the accessors for dockpanel. Dock, so it has additional properties. The dockpanel class also contains a logic that iterates its child elements and checks whether each element has the dockpanel. Dock setting value. If a value is found, it is used to locate the child element during the layout process. The use of dockpanel. Dock additional properties and such positioning functions are actually an exciting side of 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>

 

 

In WPF, most or all additional attributes are also implemented as dependency attributes. For more information, see additional properties overview.

The additional event uses a syntax format similar to "owner type. event name. Just like a non-additional event, the property value of the additional event in XAML specifies the name of the handler method called when an element is processing the event. It is not common to use additional events in wpf xaml. For more information, see the additional event overview.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.