Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 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:
Total page views :  50089
Total downloads :  8
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
ASP.Net 4 Hosting is here
Become a Sponsor

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
 About the author
 
Mahesh Chand
Mahesh is a software developer with over 13 years of experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle. If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line 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.
NEW! ANTS Performance Profiler 6.0 out now!
Attach to running process... SQL profiling... I/O profiling... Command-line profiling... Silverlight profiling... Zero overhead mode... Line-Level Timings... Find out more
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.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Aurigma Image Uploader
Aurigma Image Uploader is a versatile upload solution for a wide range of websites. Whether it's a social networking site, photo sharing service, or content management system, Aurigma can do a heavy lifting. Multiple file upload, pre-upload photo resize, etc – all your uploading users will praise you for that!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Great practical introduction by vikrenth On April 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 introduction by Mahesh On April 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 | 
MindFusion's Components
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.5.15
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.