Introduction to XAML
 
Published: 05 Oct 2006
Abstract
In this article Keyvan introduces Microsoft's new markup language, XAML, for designing user interfaces in .NET 3.0.
by Keyvan Nayyeri
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 67309/ 61

Background

EXtensible Application Markup Language (XAML) which is pronounced as Zamel is Microsoft's new markup language to define dynamic or static user interfaces for .NET applications.  XAML will be used in Windows Vista to design user interfaces, but can be applied to Windows XP or Windows 2003 as well.

XAML comes to separate the UI code from application logic code and is very similar to MVC.  XAML is tied to Windows Presentation foundation (codenamed Avalon) to build a whole user interface in .NET 3.0 and Windows Vista.

XAML is an XML child indeed.  Every XAML code must be a well-formed XML file and XAML inherits all XML definitions and rules.  We can consider it as the last part of a chain that contains HTML, XHTML and other markup languages for UI.

What makes XAML different from other XML children is what it represents.  Every XAML element represents a .NET CLR class.  This lets you to extend and work on XAML easily.

The model that XAML in conjunction with Windows Presentation Foundation provides to let developers design a rich user interface is similar to code behind and code inline model in ASP.NET.

This means you can put your application logic in a separate file or embed it inline in XAML file itself.

XAML files will be compiled to BAML files.  The advantage of BAML is it is smaller than XAML and is easier to read so it is faster to load.

Advantages of XAML

In addition to all benefits that XML or actually a markup language provides, XAML has some major and minor advantages; some of them are here:

·         Designing a user interface is easier with XAML.

·         Code for XAML is shorter than code for previous UI designing techniques and you will see it in action.

·         XAML designed user interfaces are easier to transfer and present in other environments.  For example, you can present your UI on the web or a Windows Client easily.

·         Designing a dynamic UI is absolutely easier with XAML.

·         XAML enables a new world for UI designers and lets all designers build user interfaces without having any knowledge about .NET development.  This helps end users to see better user interfaces in the near future.

XAML Development Tools

To start developing for XAML and Windows Presentation Foundation, you need to have some tools in hand.  Do not forget that this article is written some weeks after the release date of .NET Framework 3.0 RC1.  You can start developing XAML and WPF on Windows Vista, Windows XP or Windows 2003.

You need to download WinFX SDK and Visual Studio 2005 Extensions for WinFX.  Although by installing WinFX SDK you have a cool tool to develop for XAML, Visual Studio Extensions can enable a visual designer and Intellisense, and great debugging features.  I recommend downloading VS 2005 Extensions for WinFX if you have it installed on your system.

Of you do not have it, do not worry because WinFX SDK comes with an editor for XAML which is named XAMLPad.  This editor lets you to type and edit XAML markup then it generates the UI for you.  It also has some debugging features.

There are some other tools available by Microsoft or community for XAML development:

·         Microsoft Expression "Sparkle Interactive Designer"

·         MyXaml

If you are using some tools like XamlPad to write your XAML codes, you can use MSBuild to compile them, but if Visual Studio is your primary IDE for this purpose it builds them on the fly for you.

Write First Application with XAML

It is better to step in code and see the simplest XAML code in action.  Listing 1 provides a sample application that lets you to put a text in a TextBox then click on a Button.  Listing 2, which is the handler code for this click, does the rest and shows your text in a MessageBox.  The output is provided in Figure 1.

Listing 1

<Window x:Class="IntroductionToXAML.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Introduction To XAML" Height="200" Width="300"
    >
  <StackPanel>
    <TextBox Name="MyTextBox"
             Width="200"
             Height="30"
             Margin="40" />
    <Button Click="ButtonClickHandler"
            Width="60"
            Height="20">
      Click me!
    </Button>
  </StackPanel>
</Window>

Listing 2

void ButtonClickHandler(object sender, RoutedEventArgs e)
{
    MessageBox.Show(string.Format
        ("You typed '{0}' in TextBox!", MyTextBox.Text), "XAML");
}

Figure 1

Initially you can find some points from this simple code.

1.      XAML file starts with a <Window /> element as root.  This element will be the most common root element for your XAML files.

2.      Default namespace for XAML file is "http://schemas.microsoft.com/winfx/2006/xaml/presentation" and it has another "x" namespace which is set to "http://schemas.microsoft.com/winfx/2006/xaml."

3.      Main elements are embedded in a <StackPanel /> element.  StackPanel is one of the XAML elements for laying out other elements.

4.      There is no identifier for my Button.  In XAML you do not need to put a name as identifier for your controls unless you want to refer to them from other parts of your code.  This helps you to have shorter codes.  But as I want to refer to my TextBox in my code, I defined a Name attribute for it and set it to MyTextBox.

5.      My Button has a Click attribute which is set to an event handler in my code to handle the Click event of this button.

Note that I could merge Listing 1 and Listing 2 codes in one XAML file and use inline model to write my click event as you see in Listing 3.

Listing 3

<Window x:Class="IntroductionToXAML.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Introduction To XAML" Height="200" Width="300"
    >
  <StackPanel>
    <TextBox Name="MyTextBox"
             Width="200"
             Height="30"
             Margin="40" />
    <Button Click="ButtonClickHandler"
            Width="60"
            Height="20">
      Click me!
    </Button>
  </StackPanel>
  <x:Code>
    <![CDATA[
        void ButtonClickHandler(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(string.Format
                ("You typed '{0}' in TextBox!", MyTextBox.Text), "XAML");
        }
      ]]>
  </x:Code>
</Window>

Note that <x:Code /> element must be a direct child of root element in a XAML file.  Since you do not have great tools, such as Intellisense in inline model, and your code will be long and hard to read in this case, I do not recommend using inline model.

XAML Elements

I said each XAML element represents a .NET CLR class.  Most XAML elements are inherited from System.Windows.UIElement, System.Windows.FrameworkElement, System.Windows.FrameworkContentElement and System.Windows.ContentElement.  There are not any XAML elements that correspond to abstract classes in .NET CLR, but there are tons of XAML elements that are corresponded to classes that are inherited from these abstract classes.

We have four general kinds of XAML elements.

·         Root elements: Windows and Page elements are the most common root elements that you will use.  These elements sit as the root element for your XAML files and contain other elements.

·         Panel elements: These elements help you to lay out your user interface.  Common panel elements are StackPanel, DockPanel, Grid and Canvas.

·         Control elements: These elements define several types of controls in XAML and let you put a control on your UI and customize it.

·         Geometric elements: This kind of elements helps you to draw shapes and geometric graphics on your UI.  There are many Geometric elements such as LineGeometry, EllipseGeometry, PathGeometry and LineSegment.

·         Document elements: These elements are helpful when you want to deal with presentation of a document.  Inline and Block elements are two major groups of these elements that help out to make your desired look for a document.  Some famous Inline elements are Bold, LineBreak and Italic and some famous Block elements are Paragraph, List, Block, Figure and Table.  Compare these elements with some HTML elements such as <p>, <table> and <i>.

XAML Attributes

XAML attributes are equivalent to .NET class properties.  You can define attributes inline or explicit.  Explicit definitions help you when your element has several attributes and is getting larger.

Listing 4 shows an inline attribute definition for a Button's Margin attribute and Listing 5 shows an explicit attribute definition for same attribute.

Listing 4

<Button 
  Margin="5">
  Click me!
</Button>

Listing 5

<Button>
  <Button.Margin>5</Button.Margin>
  Click me!
</Button>

Object oriented nature of XAML leads to a behavior that you have seen in HTML before.  Each attribute (which is actually a class property) inherits its parent elements properties or overrides them (if you set that property).

Another key topic in XAML attributes that you should know is Attached Properties.  Some XAML elements get their attributes in other elements and these attributes are named Attached Properties.

For example when you want to use a Grid element (which is very similar to Table in HTML) to lay out your elements, to specify the position of elements in Grid's rows and elements you use Attached Properties.  Each element can get a Grid.Row and Grid.Column which represent the row and column indexes for that element in Grid control.  Listing 6 shows this in action and you can see the output in Figure 2.

Listing 6

<Window x:Class="IntroductionToXAML.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="" Height="94" Width="108"
    >
  <Grid ShowGridLines="True">
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="50" />
      <ColumnDefinition Width="50" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
      <RowDefinition Height="30" />
      <RowDefinition Height="30" />
    </Grid.RowDefinitions>
 
    <Label Grid.Column="0" Grid.Row="0">0,0</Label>
    <Label Grid.Column="0" Grid.Row="1">0,1</Label>
    <Label Grid.Column="1" Grid.Row="0">1,0</Label>
    <Label Grid.Column="1" Grid.Row="1">1,1</Label>
  </Grid>
</Window>

Figure 2

Generate User Interface Programmatically

I said one of XAML advantages is in its short code for generating a UI.  You can use programming languages to build your user interface but should avoid it when you can use XAML markup.  Listing 7 is the code equivalent for Listing 1 and Listing 2.  Obviously, you like to use XAML instead of this approach, but sometimes it is necessary to do this via code.  You can use any .NET language to start coding for Windows Presentation Foundation.

Listing 7

private TextBox MyTextBox = new TextBox();
private Button btnClick = new Button();
private StackPanel stackPanel = new StackPanel();
 
public Window1()
{
    // Create TextBox
    this.MyTextBox.Width = 200;
    this.MyTextBox.Height = 30;
    this.MyTextBox.Margin = new Thickness(40);
    this.MyTextBox.Name = "MyTextBox";
 
    // Create Button
    btnClick.Width = 60;
    btnClick.Height = 20;
    btnClick.Content = "Click me!";
    btnClick.Click += 
        new RoutedEventHandler(ButtonClickHandler);
          
    // Layout Controls
    this.stackPanel.Children.Add(MyTextBox);
    this.stackPanel.Children.Add(btnClick);
 
    this.Content = stackPanel;
}
 
void ButtonClickHandler(object sender, RoutedEventArgs e)
{
    MessageBox.Show(string.Format
        ("You typed '{0}' in TextBox!"this.MyTextBox.Text), "XAML");
}

Note that this code does not generate a Window itself!

References

These are some books that are written about XAML and WPF so far.

·         XAML In a Nutshell, written by Lori A. MacVittie (O'Reilly)

·         Programming Windows Presentation Foundation, written by Chris Sells and Ian Griffitbs (O'Reilly)

·         Applications = Code + Markup: A Guide to the Microsoft Windows Presentation Foundation, written by Charles Petzold (MS Press)

And these are some sites about XAML and WPF.

·         XAMLDev.Com: An online community about XAML and WPF with several resources

·         Microsoft Windows Presentation Foundation Community

·         Windows Presentation Foundation homepage on MSDN

·         Windows Presentation Foundation Forum

·         XAMLshare.Com: Another online community about XAML and WPF

Summary

In this article you learned about the workings of XAML.  In future articles I want to discuss XAML principles and introduce what is necessary for a beginner, but if you want to get more information about XAML and Windows Presentation Foundation there are many online communities and books about them.



User Comments

Title: Ms   
Name: Poushali Ganguly
Date: 2012-06-20 9:03:36 AM
Comment:
Thanks for this post about XAML! We extensively use in .NET Framework 3.0 & .NET Framework 4.0 technologies owing to its numerous advantages like you have mentioned in your post. To know more, visit http://www.talentica.com or write to me at info@talentica.com
Title: 2012 NFL jerseys   
Name: NIKE NFL jerseys
Date: 2012-05-20 11:29:20 PM
Comment:
[/pre]Cheap NFL,NBA,MLB,NHL
[url=http://www.jersey2shop.com/]Jerseys From China[/url]
[url=http://www.jersey2shop.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jersey2shop.com/]cheap China Jerseys[/url]
[url=http://www.jersey2shop.com/]Sports Jerseys China[/url]
[url=http://www.jersey2shop.com/NFL-Jerseys-c68/]NFL Jerseys China[/url]
[url=http://www.jersey2shop.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
NHL Jerseys China
[url=http://www.jersey2shop.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]NFL jerseys For Sale online.All Our Jerseys Are Sewn On and Directly From Chinese Jerseys Factory
[/pre]
[pre]We Are Professional China jerseys Wholesaler
[url=http://www.cheapjersey2store.com/]Wholesale cheap jerseys[/url]Cheap mlb jerseys
[url= http://www.cheapjersey2store.com/]2012 mlb all atar jerseys[/url]
[url= http://www.cheapjersey2store.com/ [/url]Cheap China Wholesael[/url]
[url= http://www.cheapjersey2store.com/]Wholesale jerseys From China[/url]
[url=http://www.cheapjersey2store.com/]2012 nike nfl Jerseys[/url]Free Shipping,Cheap Price,7 Days Deliver
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.cheapjersey2store.com/]Jerseys From China[/url]
[url=http://www.cheapjersey2store.com/NFL-Jerseys-c68]NFL jerseys China[/url]
[url=http://www.cheapjersey2store.com/NHL-Jerseys-c96/]NHL Jerseys China[/url]
[url=http://www.cheapjersey2store.com/NBA-Jerseys-c77/]NBA Jerseys China[/url]
[url=http://www.cheapjersey2store.com/MLB-Jerseys-c94/]MLB Jerseys China[/url]
[url= http://www.cheapjersey2store.com/]China Jerseys[/url],Free Shipping
[/pre]
[/pre]
We are professional jerseys manufacturer from china,wholesal
sports [url= http://www.jerseycaptain.com/]cheap jerseys sale online [/url]
[url= http://www.jerseycaptain.com/]2012 nike nfl Jerseys[/url]
[url=http://www.jerseycaptain.com/NFL-Jerseys-c68]cheap NFL jerseys China[/url]
[url=http://www.jerseycaptain.com/NHL-Jerseys-c96/]NHL Jerseys C
Title: Beginner to xml   
Name: Pradeep
Date: 2012-02-23 9:02:22 AM
Comment:
Thanks !!! .It is very helpful for beginners to know about XAML......
Title: How to add rows programmatically!   
Name: awe
Date: 2009-06-19 8:54:08 AM
Comment:
OK, I found out, it was actually adding correctly, it was just that the container shrimped the grid so all rows became too narrow. I put the grid into a scroll container, and - voilá !
Title: How to add rows programmatically?   
Name: awe
Date: 2009-06-19 8:17:39 AM
Comment:
Just to make it clear: the label, labelEnglish and textBox are labels and textbox that are created and set content on before the code you see.
Title: How to add rows programmatically?   
Name: awe
Date: 2009-06-19 8:15:10 AM
Comment:
I want to be able to add lables and text boxes to the grid content programmatically. How do I do that? I tried with the following code, but it doesn't seem to work. grid (with lowercase g) is the grid object I am working with. Grid (with uppercase G) lets me run the static methods to set column and row number (I didn't find any other way to do this).

grid.RowDefinitions.Add(new RowDefinition());
grid.Children.Add(label);
Grid.SetColumn(label, 0);
Grid.SetRow(label, grid.RowDefinitions.Count - 1);
grid.Children.Add(labelEnglish);
Grid.SetColumn(labelEnglish, 1);
Grid.SetRow(labelEnglish, grid.RowDefinitions.Count - 1);
grid.Children.Add(textBox);
Grid.SetColumn(textBox, 2);
Grid.SetRow(textBox, grid.RowDefinitions.Count - 1);
Title: how to write XAML code for sign in page in silverlight   
Name: ling
Date: 2009-05-18 6:57:58 AM
Comment:
i am quite new to silverlight n XAML..and my project need to create a login,sign up and forget password page.may i know how to write coding for all of dem.
Title: Excellent   
Name: Guru Natesh
Date: 2009-04-14 6:05:06 AM
Comment:
Awesome information abt Xaml for starters
Title: Excellent   
Name: Mr.Gren
Date: 2009-02-04 11:49:38 PM
Comment:
Very Useful for XAML beginners and VS2008 users
Title: Excellent   
Name: JohnA. Blesson
Date: 2009-01-20 2:54:45 AM
Comment:
Very Useful for XAML beginners and VS2008 users
Title: Good   
Name: Palani
Date: 2008-10-23 7:56:26 AM
Comment:
I m interest in ASP.NET. Contact my no 9600478244
Title: Good Article!!   
Name: Tanvir Ehsan
Date: 2008-09-18 4:24:42 AM
Comment:
Thanks Author Keep continuing to such quick learning guide for the beginner!!
Title: Fine   
Name: M.S. Feroz
Date: 2008-09-02 2:09:20 AM
Comment:
Excellent article for beginner. thanks
Title: Good article for biginner   
Name: Bhavesh patel
Date: 2007-04-11 8:47:02 AM
Comment:
Good article for biginner
Title: My point of View Of XAML   
Name: Zaheer Ahmed
Date: 2007-01-20 5:11:49 AM
Comment:
hi i m software engineer and currently i m working on VS.NET 2.0 and i wana switch to 3.0 this article help me to know wht is XAML Thanx
Title: Events in Windows Presentation Foundation   
Name: Keyvan Nayyeri
Date: 2006-12-14 10:22:36 AM
Comment:
Fifth part of these tutorials about Events in Windows Presentation Foundation:
http://aspalliance.com/1088_Events_in_Windows_Presentation_Foundation
Title: Animations in XAML   
Name: Keyvan Nayyeri
Date: 2006-10-25 12:36:09 AM
Comment:
Fourth part of these tutorials about Animations in XAML:
http://aspalliance.com/1050_Animations_in_XAML
Title: Layout in XAML   
Name: Keyvan Nayyeri
Date: 2006-10-09 2:07:52 PM
Comment:
Second part of these tutorials about Layout in XAML:
http://aspalliance.com/1023_Layout_in_XAML
Title: Thanks   
Name: Keyvan Nayyeri
Date: 2006-10-05 1:54:25 AM
Comment:
Thank you. I think I have many items there ;-)
Title: Added to NetFXGuide.com   
Name: Francesco
Date: 2006-10-05 1:43:36 AM
Comment:
Hi, I just added your intro to the XAML Section of NetFXGuide.com (http://www.netfxguide.com/guide/xaml.aspx).

Best,

Francesco
NetFXGuide.com

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-28 5:36:19 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search