Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » XAML » Introduction to XAML

Introduction to XAML

XAML is a new descriptive programming language developed by Microsoft. The purpose of XAML to build user interfaces for next-generation Windows operating system. This article is a basic introduction to XAML.

Author Rank:
Technologies: .NET 1.0/1.1, XAML,Windows Longhorn
Total downloads : 8
Total page views :  43043
Rating :
 4.4/5
This article has been rated :  5 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
ArticleAd
Become a Sponsor


Related EbooksTop Videos

XAML is a new descriptive programming language developed by Microsoft to write user interfaces for next generation managed applications. This article is a basic introduction to XAML.

 

The Root Element

 

The root element of the XAML must have namespace defined as following:

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

The root element of an XAML document can contain only certain elements and these elements are a Window, a Canvas, or panels. XAML has different types of panels used for different purposes. I will be talking about panels in more details in my forthcoming articles.

 

Windows and Canvas

 

Once the root element is defined, children are defined within the root element. For example, the following XAML code creates a Window and a Button as the child of the window.

 

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/
presentation
 xmlns:x="http://schemas.microsoft.com/winfx/2006/
xaml
"
>

          <Button>Hello World</Button>

</Window>

 

The <Window> element represents a window, which replaces a Windows Form or ASP.NET Web page in previous Microsoft development platforms and the <Button> element represents a button control.

 

The above code generates the following output:

 

 

Image 1. A Window generated using XAML  

 

Here is another example. In this example, I use <Canvas> element as the root element. Again, a canvas can be treated as a parent control of other child controls. 

 

<Canvas xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:def="Definition">

 

          <Button>XAML Button</Button>

 

</Canvas>

 

The above code generates output as Figure 2. As you can see from Figure 2, an XAML document is rendered directly by the browser.

 

 


Figure 2. Button control

 

XAML Control Attributes

 

Each of the elements such as <Window> or <Button> has attributes and can be set within the element itself. For example, a Button has Height, Width, Background, Foreground and other attributes, which represents height, width, foreground color, and background color of the button respectively.

 

The following code snippet sets the Id, height, width, background color, foreground color, font name and size, and content of a button. The Content attribute represents the text of the botton. 

<Button Name="btn1" Height="50" Width="200" Background="Red" Foreground="White" FontFamily="Times New Roman" FontSize="14" Content="Red Button"/> 

Figure 3 is the result of above code. As you can see from Figure 2, the button has white foreground and red background, with the size specified in the code.

 

 

Figure 3. Button with red background.

 

Like any other controls, you can also define the events of the controls within the XAML element itself. For example, the Click attribute of the <Button> represents the click event handler of the button. The following code sets the Click attribute of the button as ButtonClickMethod, which means when the button is clicked; the code written on the ButtonClickMethod will be executed. 

 

<Button Name="btn1" Height="50" Width="200" Background="Red" Foreground="White"

            FontFamily="Times New Roman" FontSize="14" Content="Red Button" Click="ButtonClickMethod"/>

 

Control Event Handlers

 

Now lets define the ButtonClickMethod. I am using C# language. The code is always written within <![CDATA[ ]]> element. My ButtonClickMethod is listed in Listing 5. As you can see from Listing 5, I can also set the button’s properties at run-time in my code as well. I also generate a message box when the button is clicked.

 

        <![CDATA[

         

            void ButtonClickMethod(object sender, EventArgs e)

            {

                btn1.Background = Brushes.Green;

                MessageBox.Show("Red Button clicked");

            }

        ]]>

 

The final code is listed in Listing 6.

 

<DockPanel>

        <Button Name="btn1" Height="50" Width="200" Background="Red" Foreground="White"

            FontFamily="Times New Roman" FontSize="14" Content="Red Button" Click="ButtonClickMethod"/>       
     <x:Code>

          <![CDATA[

         

            void ButtonClickMethod(object sender, EventArgs e)

            {

                btn1.Background = Brushes.Green;

                MessageBox.Show("Red Button clicked");

            }

        ]]>
     </x:Code>

  </DockPanel>  

 

The output of Listing 6 generates Figure 4. As you can see from this Figure, when you click on the button, it changes the color of the button to green and generates a message box saying "Red Button clicked".

 

 

Figure 4. Button click output 

 

Communication between two Controls

 

Now let's create one Windows application with a TextBox and a Button control on it. In this application, we will change the TextBox.Text property on button click event. Our final Window looks like Figure 5.

 

 

Figure 5. A Window with a TextBox and a Button control

 

The code for creating a Windows, a TextBox, and a Button is listed in Listing 7. In this code, the <Window /> element represents a Window.  

 

<Window x:Class="WindowsApplication5.Window1"

    xmlns="http://schemas.microsoft.com/winfx/avalon/2005"

    xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005"

    Title="WindowsApplication5"

    >

    <Grid Height="244" Width="469">

     <TextBox VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Column="0" Grid.ColumnSpan="1" Grid.Row="0" Grid.RowSpan="1" Margin="190,26.5,0,0" Width="202" Height="38" Name="textBox1"></TextBox>

    <Button VerticalAlignment="Top" HorizontalAlignment="Left" Grid.Column="0" Grid.ColumnSpan="1" Grid.Row="0" Grid.RowSpan="1" Margin="232,99.5,0,0" Width="135" Height="55" Name="button1" Click="ButtonClickMethod">Button</Button>

  </Grid>  

 

</Window>

 

Listing 8.

 

Now let's add code to change Text property of TextBox as listed in Listing 8. This code should look familiar. On button click event handler, we are simply setting textBox1.Text to "Button clicked" string.

    <x:Code>
    <![CDATA[

            void ButtonClickMethod(object sender, EventArgs e)

            {

               textBox1.Text = "Button clicked";            

            }

        ]]>

   </x:Code> 

Listing 9.

 

Now let's run the application and click on the button. The output looks like Figure 6.

 

 

Figure  6.

 

In-line versus Code-behind

 

Similar to ASP.NET programming model, we have choice to write code in XAML document itself or in a seperate file as code-behind. In our previous example, we used the following syntax to write in-line code.

 

    <![CDATA[

 

However, you have choice to use a seperate file and place all code in that file as code-behind file. If you want to do so, you have to tell your XAML document the file name using the following syntax. 

<Window x:Class="XamlNotePad.Window1"
xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005"
Title="XAML Notepad" Height="521" Width="801">

In the above code, the code-behind code is placed in XamlNotePad.Window1 class. The in-line code is compiled at run-time but if you have a code-behind file, you will have to compile the application before deploying it.

 

This is why XAML is HOT!

 

I did lot of work with graphics using GDI+ and graphics objects such as Rectangle, Ellipse, Line, and Path did not have any events.

 

Guess what? All of these objects in XAML have events now. In other words, I can have a mouse down event on an ellipse. That's pretty cool.

 

The following code creates an Ellipse and adds MouseDown  event handler called EllipseMouseDown. I have EllipseMouseDown defined in code-behind.

 

<Ellipse Name="MyEllipse" Height="100" Width="300" StrokeThickness="5" Stroke="Black" Fill="Gold" MouseDown="EllipseMouseDown" />

Here is the MouseDown event handler in .cs file.

void EllipseMouseDown(object sender, MouseButtonEventArgs e)
{
    MessageBox.Show("Mouse was down");
}

Now when you mouse down on the ellipse, the output looks like Figure 7.

Figure 7.

Pretty cool. huh?

Summary

 

This article is a basic introduction to XAML. In this article, you saw how to create simple user interfaces and controls using XAML. You also learnt how we can create controls and write event handlers for the controls.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Mahesh Chand
Mahesh is a software consultant, architect, author, MCP, MVP, and founder of C# Corner. He has over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries including Microsoft, Unisys, Barclay’s, Centocor (J&J), McGraw-Hill, Excelon, PMI, and University of Pennsylvania Hospital. Since year 2000, he is been working with, ASP.NET, SQL Server, C# and .NET. His latest experience and interest is Silverlight, WPF, WCF, XAML and .NET 3.5. If you need any consulting in ASP.NET, AJAX, WPF, WCF, or XAML, contact him at mahesh AT c-sharpcorner DOT com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Boost the performance of your .NET applications
“ANTS Profiler took us straight to the specific areas of our code which were the cause of our performance issues." Terry Phillips, Sr. Developer, Harley-Davidson Dealer Systems. Download your free trial of ANTS Profiler.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
ArticleAd
Become a Sponsor
Latest Comments:
Subject Posted By Posted On
Great practical introductionvikrenth4/3/2007
Just now i came to know about XAML and would love to dig into it more as i have some 30 years to work :) .i just have 9 months of xperience with pgm.Hope it would do great for me as you have suggested.Can you please tell me what are the things required to run this XAML?
Reply | Email | Delete | Modify | 
 
 
Re: Great practical introductionMahesh4/5/2007

You need to have Windows XP, Windows 2003 Server, or Windows Vista OS with Visual Studio 2005 (any edition). Download Express version from MSDN for free. After that, you need to install .NET 3.0 (WinFx SDK) and Visual Studio 2005 extensions.

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved