Page 1



What is XAML? XAML, a acronym for Extensible Application Markup Language pronounced as “zammel”. It is a declarative markup language that is used to design WPF applications. It is a variant of Standard markup language –XML(Extensible Markup language). WPF is that XAML is a completely declarative language, allowing the developer (or designer) to describe the behavior and integration of components without the use of procedural programming. XAML is a relatively simple and general-purpose declarative programming language suitable for constructing and initializing .NET objects. In XAML, elements and attributes map to classes and properties in the underlying APIs. Why XAML? 1)XAML simplifies creating a UI for WPF application. XAML is usually the most concise way to represent user interfaces or other hierarchies of objects. The specific advantage that XAML brings to WPF is that XAML is a completely declarative language, allowing the developer (or designer) to describe the behavior and integration of components without the use of procedural programming. Although it is rare that an entire application will be built completely in XAML, the introduction of XAML allows application designers to more effectively contribute to the application development cycle. Designers create visible UI elements in the declarative XAML markup, and then separate the UI definition from the business logic by using code-behind files. These code files are joined to the markup through partial class definitions. The tags that are specified in XAML like elements and attributes directly represents the instantiation of objects that are types defined in WPF or custom assemblies. This is unlike most other markup languages, which are typically an interpreted language without such backing type system facility. 2)Clear separation of design logic and business logic. One of the good application architectural principle is separation of View and Model. XAML facilitates this by allowing develop user interfaces with the separation of business logic or runtime logic. This separation of appearance and behavior has the following benefits: i) Development and maintenance costs are reduced because appearance-specific markup is not tightly integrated with behavior-specific code. ii) The use of XAML by designers and developers provides a unified platform on which visual design and application logic can be seamlessly integrated. iii)Development is more efficient because designers can implement an application's appearance simultaneously with developers who are implementing the application's behavior. Multiple design tools can be used to implement the XAML based application development like Microsoft Expression Blend , XAMLPad, Aurora by MobiForm , Zam-3D by ElectricRain etc provides an experience that suits designers such as interface for design, typesetting and illustration etc. generating XAML code. The resultant XAML can then be handed off to a developer for integration with business logic and other application-specific features while Visual Studio.NET can used by developers to code the application. In typical web page development, both layouts and specific themes are defined in markup only, but XAML is not required for either. Indeed, all elements of WPF may be coded in a CLR language like C#, VB.NET. The XAML code is ultimately compiled into a managed assembly in the same way all .NET languages are. 3)Supports multiple XAML design tools : Tools for creating XAML based design logic are as described below: a) Microsoft Expression Design Expression Design is a specialized drawing tool used to create vector-based art that can be exported as a normal image or as XAML. This tool is designed to be used by artists or designers to create art and then use another tool to integrate the art into a WPF application. For example, an artist could create a high-quality graphic with Expression Design and then hand that art off as a XAML file to a developer to incorporate business logic, using Expression Blend or another development tool. b)Microsoft Expression Blend Expression Blend is used to create WPF applications and is particularly well suited to designing UI presentation and behavior. In Blend, designer can specify the look and layout of UI controls and other application objects, create property triggers, and add animations. In addition, designer can simplify management of UI by using styles, control templates, and resources. All of these things can be done using the Blend Design Mode, or can be toggled to see and edit the XAML markup directly. When the code needs to changed such as application logic (for example, opening a C# file), Blend opens the file in Visual Studio or another development tool. c)WPF Designer The WPF Designer is part of Visual Studio 2008 and provides visual design support. While Expression Blend is a powerful tool that allows you to fully customize your application's UI without editing the XAML, the WPF Designer's graphical user interface can also be used to build the UI of an app within Visual Studio. The user interfaces can be built by dragging controls from the Toolbox and setting properties in the Properties window. The control properties also can be changed by editing XAML directly in the XAML editor d)XAMLPad XAMLPad is a Windows SDK tool that provides the following features: a)In-place editing and display of XAML content. b)XAML markup is automatically saved to the file XamlPad_save.xaml. c)Auto parse and refresh modes provide XAML syntax validation and redisplay of content. d)Supports basic text editing commands like copy, paste, and undo. e)The parsing errors-i.e., invalid XAML displayed in red. f)XAML errors are displayed in the status bar on bottom left of the main window. g)Expansion of XAML content into a visual tree allows designer to view property values of content. h) A ready XAML file can be loaded into XamlPad by passing the file name as a command-line argument . 4)It’s shorter than code: XAML is more readable than code and shorter as well. Let us consider the code example below. This example explains how to create WPF application writing managed code that is –Without XAML. Example 1) Writing WPF application using Managed code: using System; namespace DemoXAML { class SimpleWindow : Window { public SimpleWindow () { this.Title = "XAML Demo"; StackPanel panel = new StackPanel(); TextBlock textBlock = new TextBlock(); textBlock.Text = "Welcome to the world of WPF"; Button btnMsg = new Button(); btnMsf.content="Click Here": btnMsg .Click += btnMsg_Click; panel.Children.Add(textBlock); panel.Children.Add(btnMsg ); this.Content = panel; } }} Now let us look at the XAML equivalent of the above code to create WPF application which is as shown below : <Window x:Class=“DemoXAML.SimpleWindow" xmlns="" xmlns:x="" Title=" XAML Demo - XAML" Height="300" Width="300”> <StackPanel> <TextBlock Name="txtBlock"></TextBlock> <Button Name="btnMsg" Content="Click here!" Click="btnMsg_Click"></Button> </StackPanel> </Window> The event handler would go in Code behind file. From the above two code snippets it is quite obvious that XAML code is shorter than the Managed WPF application code. Creating XAML Based WPF UI’s: To create WPF application design logic, markup tags for WPF elements are defined in .xaml files(StuRegistration.xaml) are used and the business logic for the same would exist in code behind file - .xaml.cs (Example : StuRegistration.xaml.cs”) Note : XML : XML is a markup language standardized by W3C , that is language neutral, platform neutral and promotes interoperability.


What is .xaml file? A .xaml file contains XAML equivalent tags for WPF elements that are used to code WPF UI logic . <Window x:Class="LayoutDemos.BasicDemo" xmlns="" xmlns:x="" Title="Basic XAML Demo" Height="300" Width="300"> <StackPanel> <TextBlock Name="txttitle">XAML Basics Demo</TextBlock> <TextBlock Name="txtBlock"></TextBlock> <Button Name="btnMsg" Content="Click here!" Click="btnMsg_Click"></Button> </StackPanel> </Window> In WPF applications, all of the forms created have .xaml extensions. Like XML, a XAML file must have only one root element, in order to be both a well-formed XML file and a valid XAML file. In the WPF application model, the root element of XAML could be a Window ,Page or Frame. It could also be any of the content models like Canvas, DockPanel , Grid etc. In the root element example, the prefix x: is used to map the XAML namespace, which is the dedicated XAML namespace that supports XAML language constructs. The .xaml file holds the design logic while .xaml.cs holds the business logic or runtime logic . The x:class namespace prefix plays the role of linking these two files. x:class The x namespace prefix (x:class), the Class attribute tells the XAML parser to generate a new class with the specified name. That class derives from the class thatâ&#x20AC;&#x2122;s named by the XML element. In order to associate the XAML with code, an attribute x:Class is used . The x:Class attribute links the XAML file with a procedural code file, the code-behind file. This attribute must be applied to a top-level Page, Window, or Application object. The x:Class attribute essentially informs the compiler to link the root element of your XAML file. When compiled, the markup compiler generates a partial class code file that will connect your XAML with your procedural code. The value of the x:Class attribute can be any string that identifies the name of a class in your application. In other words, the above example the code behind file includes a definition of a partial class named BasicDemo from LayoutDemos namespace, which derives from the base Window class. The x:class attribute will connect XAML with this generated partial class code when compiled. What is .xaml.cs file? Visual Studio creates a partial class where event handling code can be placed. For example, if you create an application named LayoutDemos , which contains a window named BasicDemo (as in the previous example), Visual Studio will provide developer a basic skeleton of a partial class. This class includes all of the necessary business logic and event handlers for all the elements on the form. namespace LayoutDemos { /// <summary>Interaction logic for BasicDemo .xaml</summary> public partial class BasicDemo : Window { public BasicDemo () { InitializeComponent(); } } }


Namespaces are logical containers that group similar or related objects. The .NET Framework uses namespaces to uniquely identify and group a set of types. In XML, a namespace is a way to uniquely identify and group a set of elements. XAML maps each element to its corresponding type in the .NET Framework and, as such, identifies the types by the specified namespace. XML namespace concept: The xmlns attribute is a specialized attribute in the world of XML thatâ&#x20AC;&#x2122;s reserved for declaring namespaces. The .xaml file contains the root element contains the attributes xmlns and xmlns:x. There are two namespaces as described below: 1) Core WPF namespace: 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. Xmlms= The default XAML namespace is mapped to the WPF namespace It includes all the WPF classes, including the controls you use to build user interfaces. 2) XAML specific namespace: This namespace is mapped to the prefix x. That means you can apply it by placing the namespace prefix before the element name (as in <x:ElementName>). xmlns:x= is the XAML namespace. It includes various XAML utility features that allow that decides how a document would be interpreted. This namespace is mapped to the prefix x. That is, it can be applied by placing the namespace prefix before the element name (Example â&#x20AC;&#x201C; x:class or x:key). (Note : A prefix is a name that is given to a namespace that can be used throughout the XAML file to indicate an element or attribute belongs to a specific namespace. The XAML compiler will use this for locating the appropriate .NET type for mapping.)


XAML basics XAML Objects and Elements The tags that are specified in XAML like elements and attributes map to pre-define WPF or custom classes and properties in the underlying APIs. Example Button maps to instance of Button class of WPF API . How to define elements in XAML? To define elements in XAML, firstly mention the name of the element preceded by opening angle bracket(<) that would be instantiated . This is then followed by the multiple element attribute declarations . To complete tag definition use a closing angle bracket (>). In the example <StackPanel> <Button Background=“Pink" Foreground=“Blue" Content=“Click Me!"/> </StackPanel> This is equivalent to the following procedural code: Button btn = new Button(); btn.Background = Brushes.Pink; btn.Foreground = Brushes.Blue; btn.Content = "Click Me!"; This specifies two object elements: <StackPanel> and <Button .../>. The object elements StackPanel and Button each map to the WPF classes from WPF assemblies. The presence of object element tag, instructs XAML processing to create a new instance. Each instance is then created by calling the default constructor of the underlying type when the XAML is parsed and loaded. For XAML object elements the properties of an object can often be expressed as attributes. Attribute syntax is the XAML markup syntax that sets a value for a property by declaring an attribute on an existing object element. The attribute name must match the CLR member name of the property of the class that backs the relevant object element. The attribute name is followed by an assignment operator (=). Similar to XML, in XAML, the value of an attribute is always specified as a string that is contained within quotation marks as shown in one more example below. The object properties can be set by using specific XAML attributes for the elements. XAML attributes map to CLR properties. <Window x:Class=”XAMLTest.Window1” xmlns=”” xmlns:x=”” Title=” XAMLDemo” Height=”350” Width=”350”> <Grid></Grid> </Window> This is equivalent to the following procedural code: Window1.Title = “XAMLDemo”; Window1.Height = 350; Window1.Width = 350; In this example, Title, Height, and Width are properties of the .NET Window object, represented by the Window element.


In XML, the value of an attribute are always specified as string that is enclosed in quotation mark. In XAML, other object elements can be assigned to be the value of a property by using the property element syntax. The WPF element property can be specified as <elementTypeName.propertyName> form with the value of the property is specified within, which is then followed by the property element closing angle bracket - </elementTypeName.propertyName> Like other markup languages, the syntax specifically begins with a left angle bracket (<), followed immediately by the type name of the class or structure that the property element syntax is contained within. This is followed immediately by a single dot (.), then by the name of a property, then by a right angle bracket (>). As with attribute syntax, that property must exist within the declared public members of the specified type. The value to be assigned to the property is contained within the property element. Typically, the value is given as one or more object elements, because specifying objects as values is the scenario that property element syntax is intended to address. Finally, an equivalent closing tag specifying the same elementTypeName.propertyName combination must be provided, in proper nesting and balance with other element tags. When to use property element syntax? In XAML, sometimes the object or information necessary to provide the property value cannot be expressed using the typical elementâ&#x20AC;&#x2122;s attribute value syntax. For these cases, a different syntax known as property element syntax is used. Typical example of such case would be defining collections of brushes to color the buttons background or as defining the collection og menu item for the menu bar or for the context menu.


Attached Properties : A new programming concept introduced in XAML, whereby properties can be owned and defined by a particular type, but set as attributes or property elements on any element. Example <Border Height="25" Background="LemonChiffon" BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Bottom"> In the above example, the border is applied to the bottom docking region of the DockPanel layout . Let us look at another example where the checkbox is anchored at the top region of the DcokPanel. <DockPanel> <CheckBox DockPanel.Dock="Top">Hello</CheckBox> </DockPanel>


Attached Properties : A new programming concept introduced in XAML, whereby properties can be owned and defined by a particular type, but set as attributes or property elements on any element. Example <Border Height="25" Background="LemonChiffon" BorderBrush="Black" BorderThickness="1" DockPanel.Dock="Bottom"> In the above example, the border is applied to the bottom docking region of the DockPanel layout . Let us look at another example where the checkbox is anchored at the top region of the DcokPanel. <DockPanel> <CheckBox DockPanel.Dock="Top">Hello</CheckBox> </DockPanel>


In XAML, the event handler are associated with the XAML elements by using attribute value syntax. These event handlers are defined code behind file .xaml.cs. Example : <!-- Test.xaml  <Button Name=“btnCalculate” Click=“btnMessage_click”/> Here the Button tag has attribute Click with the value btnMessage_click. That means the buttons click event handler is associated with the attribute in the .xaml file while the event handler is defined the .xaml.cs file public partial class Test : Window { public Test ) { ..} void btnMessage_click (Object sender, RoutedEventArgs e) { Button button = sender as Button; button.Content = “welcome to WPF!!!"; } } Or let us look at one more example where click event handler for menu item is define in the code behind file. .xaml file includes : <MenuItem Name=“mnuServices” Header=“Services“ Click=“mnuServices_Click>First item</MenuItem> <MenuItem Name=“mnuProducts” Header=“Products“ Click=“mnuProducts_Click”>First item</MenuItem> .xmal.cs would include : void mnuServices_Click (Object sender, RoutedEventArgs e) { ……………………….} void mnuProducts_Click (Object sender, RoutedEventArgs e) {………………………. } In the above example, the menu items click event are specified as attribute values in the XAML markup while the event handlers are defined in the cod behind file.


In XAML, a markup extensions is a specialized syntax that sets a property in a nonstandard way. A markup extension is a feature of XAML whereby you can specify an object reference by having the markup extension process the attribute string and return the object to a XAML loader. XAML Markup Extensions: 1) x:Type: Constructs a Type reference based on a type name. 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. In the example below a style has been defined as window level resource. This style is applicable to Button as the style attribute TargetType is set to Button. <Window.Resources> <Style TargetType="Button" > <Setter Property="FontFamily" Value="Times New Roman" /> <Setter Property="FontSize" Value="18" /> <Setter Property="FontWeight" Value="Bold" /> </Style> </Window.Resources> 2) x:Static: Enables a reference that returns a static value that is not otherwise a XAML-compatible property. References any static by-value code entity that is defined in a Common Language Specification (CLS)–compliant way. The static property that is referenced can be used to provide the value of a property in XAML. Syntax:<object property="{x:Static prefix:typeName.staticMemberName}" .../> XAML Values prefix Optional. A prefix that refers to a mapped, non-default XAML namespace. prefix is shown explicitly in the usage because you rarely reference static properties that come from a default XAML namespace. See Remarks. typeName Required. The name of the type that defines the desired static member. staticMemberName Required. The name of the desired static value member (a constant, a static property, a field, or an enumeration value). Now let us see an example to use x:static markup extension. <Button ... Foreground="{x:Static SystemColors.ActiveCaptionBrush}" > In the above example, the foreground color of the button is set to static member –ActiveCaptionBrush from SystemColors. 3)x:Null : Specifies null as a value for a XAML member. Example : <Button Name=“btnCalculate” style={x:Null} >Calculate</Button> In the above example the style effect of the button is set to null that is, the style will not be applicable to button. 4) x:Array : Provides general support for arrays of objects in XAML through a markup extension. This corresponds to the x:ArrayExtension XAML type in <x:Array Type="sys:String" xmlns:x="" xmlns:sys="clr-namespace:System;assembly=mscorlib"> <sys:String>Hello</sys:String> <sys:String>World</sys:String> </x:Array> 2) WPF Markup Extensions: •StaticResource :Provides a value for a XAML property by substituting the value of an already defined resource. Example: <Style TargetType="TextBlock" x:Key="TitleText"> <Setter Property="Background" Value="Blue"/> <Setter Property="DockPanel.Dock" Value="Top"/> <Setter Property="FontSize" Value="18"/> <Setter Property="Foreground" Value="#4E87D4"/> <Setter Property="FontFamily" Value="Trebuchet MS"/> <Setter Property="Margin" Value="0,40,10,10"/> </Style> <TextBlock Style="{StaticResource TitleText}">Title</TextBlock> (Note : Creating and using Styles will be covered in the Resources session) •DynamicResource : Provides a value for a XAML property by deferring that value to be a runtime reference to a resource. A dynamic resource reference forces a new lookup each time that such a resource is accessed DynamicResource Markup Extension is expression are evaluated when the application is actually is run. •Binding : Provides a data bound value for a property, per the data context that applies to the element Example: <Label Height="28" Margin="76,86,82,0" Name=“lblName“ VerticalAlignment="Top“ Content="{Binding ElementName=comboBox1, Path=SelectedItem.Content}"> </Label> (Note : Creating and using Binding will be covered in the Data Binding session) •TemplateBinding : Links the value of a property in a control template to be the value of a property on the templated control. Syntax: <object property="{TemplateBinding Property=targetProperty}" .../> Where propertyName :DependencyProperty.Name of the property being set in the setter. targetProperty :A dependency property that exists on the type being templated, specified by its DependencyProperty.Name. (Note : Details on Control template is beyond the cope of this session.)


Custom Types in XAML: There are 2 ways to define: Custom classes that are used in XAML can be defined in two distinct ways: within the code-behind or other code that produces the primary Windows Presentation Foundation (WPF) application, or as a class in a separate assembly, such as an executable or DLL used as a class library. Rules for writing custom class to be used as a XAML element : In order to be able to be instantiated as an object element, the class must meet the following requirements: a) The custom class must be public and support a default (parameterless) public constructor. b) The custom class must not be a nested class. Nested classes and the "dot" in their general CLR usage syntax interfere with other WPF and/or XAML features such as attached properties. In addition to enabling object element syntax, your object definition also enables property element syntax for any other public properties that take that object as the value type. This is because the object can now be instantiated as an object element and can fill the property element value of such a property. XAML provides a syntax to use custom types from namespace other WPF namespace Syntax: xmlns:Prefix="clr-namespace:Namespace;assembly=AssemblyNameâ&#x20AC;&#x153; a) Prefix : It is the XML prefix you want to use to indicate that namespace in your XAML markup. b) clr-namespace: The CLR namespace declared within the assembly that contains the public types to expose as elements. It includes : 1)Namespace :It is the fully qualified .NET namespace name. 2) AssemblyName: It is the assembly where the type is declared, without the .dll extension.


The custom types that are defined in any common language runtime (CLR) language, can be accessed using XAML markup. So developers can make use of Windows Presentation Foundation (WPF)-defined types and your custom types within the same markup file, typically by mapping the custom types to a XAML namespace prefix. Let’s take a look at simple example to create a simple type to store state information. Our class has only two properties, state name and its capital, but we can make as much properties as we want. Here is a simple C# code to create that type. Namespace StateList { public class StateInfomation { public String Name { get; set; } public String Capital { get; set; } } } Now if we want to use that class in XAML, then we first have to include the reference of namespace in XAML. Suppose this class is defined in xaml namespace (its name shouldn’t necessary be xaml, it can be anything according to the rule of names in C#). Here is a simple code to use this namespace in XAML. <Window x:Class="xaml.Window1" xmlns="" xmlns:x="" xmlns:State="clr-namespace:StateList" Title="XAML" Height="300" Width="300"> <StackPanel> ……………………………… <State:StateInfomation Name="Maryland" Capital="Annapolis"/> </StackPanel> </Window>


Using Collections in XAML There are four ways to declare a CLR object collection in XAML: x:Array, ArrayList in standard XAML declarations. Let us discuss each one here. Consider the Class named Composer from the CollectionDemo namespace. Namespace CollectionDemo { public class Composer { private string m_name; private int m_birth; public Composer() {} public string Name { get { return m_name; } set { m_name = value; } } public int Birth { get { return m_birth; } set { m_birth = value; } } } } Using x:Array: <x:Array x:Key="ComposerList" Type="{x:Type custom:Composer}"> <custom:Composer Name=“Amenda" Birth=“1982"/> <custom:Composer Name=“Dina" Birth="1980"/> <custom:Composer Name=“Mischel" Birth=“1979"/> </x:Array> Using ArrayList The well-known ArrayList CLR class could also be used similarly to x:Array, but it is somewhat less concise to use. First, add the following namespace mapping: xmlns:coll="clr-namespace:System.Collections;assembly=mscorlib“ Then, we only need to modify the previous snippet slightly: <coll:ArrayList x:Key="ComposerCollection"> <custom:Composer Name=“Amenda" Birth=“1982"/> <custom:Composer Name=“Dina" Birth="1980"/> <custom:Composer Name=“Mischel" Birth=“1979"/> <coll:ArrayList> (Note : Binding the control with the data source will be covered in the Data Binding Session).








WPF XAML windows

Read more
Read more
Similar to
Popular now
Just for you