Wednesday, October 14, 2009

XAML



Chapter 3 -
Windows Presentation Framework
Microsoft Visual Studio 2008 Programming
by Jamie Plenderleith and Steve Bunn 
McGraw-Hill/Osborne © 2009























XAML


XAML is a language based on XML that is designed specifically for creating .NET interface objects. Because XAML can be written by nondevelopers (with a bit of coding experience) or through the use of other tools such as the Expression suite, it allows the appearance and “look and feel” of applications and application objects to be created separately from the application code itself. Another advantage is that XAML can handle not just WPF objects, but also other objects.


One of the limitations of using XAML files is finding an editor that alleviates the hassle of hand-editing. Visual Studio 2008 includes extensions for graphic design of XAML files, and the .NET Framework 3.0 extension does much the same for Visual Studio 2005. In those environments, a Design window acts like the older Windows Form Designer. Also available from the Windows SDK is the XAMLPad tool, which is a fairly simple visual editor.


In the XAML code for MyWindow.xaml, the root Window element declares a portion of a class called SimpleWPFApplication. The two xmlns declarations retrieve the namespaces for XAML, the first for WPF and the second for XAML. Then, a button is defined with specific properties.


If you think of XAML as providing a direct mapping from XML to .NET, the coding becomes clearer. In essence, each XAML element maps to a .NET class. XAML attributes are .NET properties or, in some cases, events (like a button click event). What XAML does not have are the details of the operations performed in events, for example. For this, a code-behind file is used. Code-behind files, by convention, are .xaml.cs files for C# and .xaml.vb file for VB.NET, and contain the operations for the XAML file.


The partial keyword for the MyWindow class tells the compiler that an XAML-generated class is associated with this class, together making the complete class. In this code, MyWindow calls the InitializeComponent method to handle the button click event. In fact, even more of the code could be moved into the XAML file, leaving only a skeleton in the code-behind file to launch the application. You could, for example, define the class in the XAML file and leave the xaml.cs file strictly for the event handler. Deciding how to balance the code between XAML and code-behind files is left for each developer, some of whom prefer to move as much as possible to the XAML file, while others put only the interface definitions in the XAML file.


























No comments:

Post a Comment