Xaml guide pdf download
The basic, native handling of how strings are converted into other object types or primitive values is based on the String type itself, along with native processing for certain types such as DateTime or Uri.
But many WPF types or members of those types extend the basic string attribute processing behavior in such a way that instances of more complex object types can be specified as strings and attributes.
Thickness indicates measurements within a nested rectangle and is used as the value for properties such as Margin. By placing a type converter on Thickness , all properties that use a Thickness are easier to specify in XAML because they can be specified as attributes. The following example uses a type conversion and attribute syntax to provide a value for a Margin :.
The previous attribute syntax example is equivalent to the following more verbose syntax example, where the Margin is instead set through property element syntax containing a Thickness object element. The four key properties of Thickness are set as attributes on the new instance:.
There are also a limited number of objects where the type conversion is the only public way to set a property to that type without involving a subclass, because the type itself doesn't have a parameterless constructor. An example is Cursor. For typical WPF scenarios, you use a root element that has a prominent meaning in the WPF app model for example, Window or Page for a page, ResourceDictionary for an external dictionary, or Application for the app definition.
The root element also contains the attributes xmlns and xmlns:x. These attributes indicate to a XAML processor which XAML namespaces contain the type definitions for backing types that the markup will reference as elements.
The xmlns attribute specifically indicates the default XAML namespace. Within the default XAML namespace, object elements in the markup can be specified without a prefix.
This usage of xmlns to define a scope for usage and mapping of a namescope is consistent with the XML 1. The xmlns attributes are only strictly necessary on the root element of each XAML file. This is enabled through configuration that is part of your project build file and the WPF build and project systems. This x: prefix is used for mapping this XAML namespace in the templates for projects, in examples, and in documentation throughout this SDK.
The following is a listing of the most common x: prefix programming constructs you will use:. You must have such a class to support code-behind per the WPF programming model, and therefore you almost always see x: mapped, even if there are no resources. In general, you will frequently use a WPF-defined equivalent property for x:Name. Such properties map specifically to a CLR backing property and are thus more convenient for app programming, where you frequently use run-time code to find the named elements from initialized XAML.
The most common such property is FrameworkElement. You might still use x:Name when the equivalent WPF framework-level Name property isn't supported in a particular type. This occurs in certain animation scenarios.
This is used to specify attributes that take Type , such as Style. TargetType , although frequently the property has native string-to- Type conversion in such a way that the x:Type markup extension usage is optional.
For your own custom assemblies, or for assemblies outside the WPF core of PresentationCore , PresentationFramework and WindowsBase , you can specify the assembly as part of a custom xmlns mapping.
You can then reference types from that assembly in your XAML, so long as that type is correctly implemented to support the XAML usages you are attempting. The following is a basic example of how custom prefixes work in XAML markup. The prefix custom is defined in the root element tag, and mapped to a specific assembly that is packaged and available with the app.
An instance of this NumericUpDown control is declared as an object element, using the prefix so that a XAML parser knows which XAML namespace contains the type, and therefore where the backing assembly is that contains the type definition. Within a project, the XAML is written as a. In the examples so far, you have seen several buttons, but none of these buttons had any logical behavior associated with them yet. The primary application-level mechanism for adding a behavior for an object element is to use an existing event of the element class, and to write a specific handler for that event that is invoked when that event is raised at run-time.
The event name and the name of the handler to use are specified in the markup, whereas the code that implements your handler is defined in the code-behind. Notice that the code-behind file uses the CLR namespace ExampleNamespace and declares ExamplePage as a partial class within that namespace.
This parallels the x:Class attribute value of ExampleNamespace. ExamplePage that was provided in the markup root. When you provide code-behind that also defines the same partial class, the resulting code is combined within the same namespace and class of the compiled app.
If you don't want to create a separate code-behind file, you can also inline your code in a XAML file. However, inline code is a less versatile technique that has substantial limitations. A particular event feature that is fundamental to WPF is a routed event.
Routed events enable an element to handle an event that was raised by a different element, as long as the elements are connected through a tree relationship. When specifying event handling with a XAML attribute, the routed event can be listened for and handled on any element, including elements that don't list that particular event in the class members table.
This is accomplished by qualifying the event name attribute with the owning class name. Click on the StackPanel object element, with your handler name as the attribute value. For more information, see Routed Events Overview.
By default, the object instance that is created in an object graph by processing a XAML object element doesn't have a unique identifier or object reference. In contrast, if you call a constructor in code, you almost always use the constructor result to set a variable to the constructed instance, so that you can reference the instance later in your code. To provide standardized access to objects that were created through a markup definition, XAML defines the x:Name attribute. You can set the value of the x:Name attribute on any object element.
In your code-behind, the identifier you choose is equivalent to an instance variable that refers to the constructed instance. In all respects, named elements function as if they were object instances the name references that instance , and your code-behind can reference the named elements to handle run-time interactions within the app. This connection between instances and variables is accomplished by the WPF XAML markup compiler, and more specifically involve features and patterns such as InitializeComponent that won't be discussed in detail in this article.
Certain other classes also provide property-level equivalents for x:Name , which is also usually defined as a Name property. The x:Name values will provide an identifier to a XAML element that can be used at run-time, either by specific subsystems or by utility methods such as FindName.
The following example sets Name on a StackPanel element. Then, a handler on a Button within that StackPanel references the StackPanel through its instance reference buttonContainer as set by Name. Just like a variable, the XAML name for an instance is governed by a concept of scope, so that names can be enforced to be unique within a certain scope that is predictable.
However, other markup sources can interact with a page at run-time, such as styles or templates within styles, and such markup sources often have their own XAML namescopes that don't necessarily connect with the XAML namescope of the page.
XAML specifies a language feature that enables certain properties or events to be specified on any element, even if the property or event doesn't exists in the type's definitions for the element it's being set on. The properties version of this feature is called an attached property, the events version is called an attached event.
Attached properties in XAML are typically used through attribute syntax. In attribute syntax, you specify an attached property in the form ownerType. Superficially, this resembles a property element usage, but in this case the ownerType you specify is always a different type than the object element where the attached property is being set.
The most common scenario for attached properties is to enable child elements to report a property value to their parent element. The following example illustrates the DockPanel. Dock attached property. The DockPanel class defines the accessors for DockPanel. Dock and owns the attached property. The DockPanel class also includes logic that iterates its child elements and specifically checks each element for a set value of DockPanel.
If a value is found, that value is used during layout to position the child elements. Use of the DockPanel. Dock attached property and this positioning capability is in fact the motivating scenario for the DockPanel class. In WPF, most or all the attached properties are also implemented as dependency properties.
For more information, see Attached Properties Overview. Attached events use a similar ownerType. Just like the non-attached events, the attribute value for an attached event in XAML specifies the name of the handler method that is invoked when the event is handled on the element.
For more information, see Attached Events Overview. However, not all classes can be mapped to elements. Abstract classes, such as ButtonBase , and certain non-abstract base classes, are used for inheritance in the CLR objects model.
Base classes, including abstract ones, are still important to XAML development because each of the concrete XAML elements inherits members from some base class in its hierarchy. Often these members include properties that can be set as attributes on the element, or events that can be handled.
When designing UI, you will use various shape, panel, decorator, or control classes, which all derive from FrameworkElement. The combination of attributes at the element level and a CLR object model provides you with a set of common properties that are settable on most concrete XAML elements, regardless of the specific XAML element and its underlying type.
XAML is a markup language that directly represents object instantiation and execution. That's why elements created in XAML have the same ability to interact with system resources network access, file system IO, for example as your app code does. XAML also has the same access to the system resources as the hosting app does. For more information, see Code Access Security differences.
This capability could be used to:. The key to these scenarios is the XamlReader class and its Load method. The input is a XAML file, and the output is an object that represents all of the run-time tree of objects that was created from that markup. You then can insert the object to be a property of another object that already exists in the app.
As long as the property is in the content model and has display capabilities that will notify the execution engine that new content has been added into the app, you can modify a running app's contents easily by dynamically loading in XAML. Skip to main content. This browser is no longer supported. If you use Visual Studio's IntelliSense for XAML in the XML editor, the IntelliSense and its drop-downs do a great job of coalescing the inheritance and providing an accurate list of attributes that are available for setting once you've started with an object element for a class instance.
Some types define one of their properties such that the property enables a XAML content syntax. Or, you can set the property to an inner text value by providing that inner text directly within the owning type's object element tags.
XAML content properties support straightforward markup syntax for that property and makes the XAML more human-readable by reducing the nesting. For example, the Child property page for Border shows XAML content syntax instead of property element syntax to set the single-object Border. Child value of a Border , like this:. If the property that is declared as the XAML content property is the Object type, or is type String , then the XAML content syntax supports what's basically inner text in the XML document model: a string between the opening and closing object tags.
For example, the Text property page for TextBlock shows XAML content syntax that has an inner text value to set Text , but the string "Text" never appears in the markup.
Here's an example usage:. If a XAML content property exists for a class, that's indicated in the reference topic for the class, in the "Attributes" section. Look for the value of the ContentPropertyAttribute. This attribute uses a named field "Name". One important XAML syntax rule we should mention is that you can't intermix the XAML content property and other property elements you set on the element.
The XAML content property must be set entirely before any property elements, or entirely after. For example this is invalid XAML:.
All of the syntaxes shown thus far are setting properties to single objects. But many UI scenarios require that a given parent element can have multiple child elements. For example, a UI for an input form needs several text box elements, some labels, and perhaps a "Submit" button. Still, if you were to use a programming object model to access these multiple elements, they would typically be items in a single collection property, rather than each item being the value of different properties.
XAML supports multiple child elements as well as supporting a typical backing collection model by treating properties that use a collection type as implicit, and performing special handling for any child elements of a collection type. Many collection properties are also identified as the XAML content property for the class. The combination of implicit collection processing and XAML content syntax is frequently seen in types used for control compositing, such as panels, views, or items controls.
It might at first appear that XAML is enabling a "set" of the read-only collection property. In reality, what XAML enables here is adding items to an existing collection. Typically there is a backing property such as an indexer or Items property that refers to specific items of the collection. Generally, that property is not explicit in the XAML syntax. For collections, the underlying mechanism for XAML parsing is not a property, but a method: specifically, the Add method in most cases.
When the XAML processor encounters one or more object elements within a XAML collection syntax, each such object is first created from an element, then each new object is added in order to the containing collection by calling the collection's Add method. When a XAML parser adds items to a collection, it is the logic of the Add method that determines whether a given XAML element is a permissible item child of the collection object.
Many collection types are strongly typed by the backing implementation, meaning that the input parameter of Add expects that whatever is passed must be a type match with the Add parameter type. For collection properties, be careful about when you try to specify the collection explicitly as an object element.
A XAML parser will create a new object whenever it encounters an object element. If the collection property you're trying to use is read-only, this can throw a XAML parse exception. Just use the implicit collection syntax, and you won't see that exception. All properties that support being set in XAML will support attribute or property element syntax for direct value setting, but potentially will not support either syntax interchangeably.
Some properties do support either syntax, and some properties support additional syntax options like a XAML content property. The type of XAML syntax supported by a property depends on the type of object that the property uses as its property type.
If the property type is a primitive type, such as a double float or decimal , integer, Boolean, or string, the property always supports attribute syntax. You can also use attribute syntax to set a property if the object type you use to set that property can be created by processing a string.
For primitives, this is always the case, the type conversion is built in to the parser. However, certain other object types can also be created by using a string specified as an attribute value, rather than an object element within a property element. For this to work, there has to be an underlying type conversion, supported either by that particular property or supported generally for all values that use that property type.
The string value of the attribute is used to set properties that are important for the initialization of the new object value.
Potentially, a specific type converter can also create different subclasses of a common property type, depending on how it uniquely processes information in the string. Object types that support this behavior will have a special grammar listed in the syntax section of the reference documentation. Sometime's it's informative to read the XAML in a similar way to how a XAML parser must read it: as a set of string tokens encountered in a linear order.
In the following syntax, objectName is the object you want to instantiate, propertyName is the name of the property that you want to set on that object, and propertyValue is the value to set. Either syntax enables you to declare an object and set a property on that object.
Although the first example is a single element in markup, there are actually discrete steps here with regard to how a XAML processor parses this markup.
First, the presence of the object element indicates that a new objectName object must be instantiated. Only after such an instance exists can the instance property propertyName be set on it.
Another rule of XAML is that attributes of an element must be able to be set in any order. Which order you use is a matter of style. Similar to the property element syntax, the attached property syntax contains a dot, and the dot holds special meaning to XAML parsing.
Specifically, the dot separates the provider of the attached property, and the property name. PropertyName Here is an example of how you can set the attached property Canvas.
Left in XAML:. You can set the attached property on elements that don't have a property of that name in the backing type, and in that way they function somewhat like a global property, or an attribute defined by a different XML namespace like the xml:space attribute. For more info, see Attached properties overview. If the member is a read-write property you can set such a property by providing an attribute value.
You identify which enumeration value to use as the value of the property by using the unqualified name of the constant name. For example here's how to set UIElement. Here the "Visible" as a string is directly mapped to a named constant of the Visibility enumeration, Visible.
This links to the enumeration page where you can discover the named constants for that enumeration. Enumerations can be flagwise, meaning that they are attributed with FlagsAttribute. If you need to specify a combination of values for a flagwise enumeration as a XAML attribute value, use the name of each enumeration constant, with a comma , between each name, and no intervening space characters. In rare cases you'll see a XAML syntax where the type of a property is an interface.
In the XAML type system, a type that implements that interface is acceptable as a value when parsed. There must be a created instance of such a type available to serve as the value. It's hinting at your eventual usage in your own XAML files, but without being over-prescriptive about the values you can use.
So usually the usage describes a type of grammar that mixes literals and placeholders, and defines some of the placeholders in the XAML Values section. For example, you can set Visibility as an attribute on any UIElement derived class using a deep inheritance. So don't take the element name shown in any XAML usage syntax too literally; the syntax may be viable for elements representing that class, and also elements that represent a derived class.
In cases where it's rare or impossible for the type shown as the defining element to be in a real-world usage, that type name is deliberately lowercased in the syntax. For example, the syntax you see for UIElement. Visibility is :. XAML usage sections also use various generalized placeholders. These placeholders aren't redefined every time in XAML Values , because you'll guess or eventually learn what they represent.
We think most readers would get tired of seeing them in XAML Values again and again so we left them out of the definitions. For reference, here's a list of some of these placeholders and what they mean in a general sense:. Skip to main content.