BUY THIS BOOK
Add to Cart

Print Book $29.99


Add to Cart

PDF $23.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £20.99

What is this?

Looking to Reprint or License this content?


XAML in a Nutshell
XAML in a Nutshell

By Lori A. MacVittie
Book Price: $29.99 USD
£20.99 GBP
PDF Price: $23.99

Cover | Table of Contents


Table of Contents

Chapter 1: Introducing XAML
XAML (pronounced "Zamel") stands for eXtensible Application Markup Language. It is Microsoft's new declarative language for defining application user interfaces. XAML provides an easily extensible and localizable syntax for defining user interfaces separated from application logic, similar to the object-oriented technique for developing n-tier applications with a MVC (Model-View-Controller) architecture.
XAML was created by Microsoft expressly for the purpose of interfacing with its .NET Framework on its Windows Vista (formerly codenamed "Longhorn") operating system through the WinFX (codename "Avalon") presentation subsystem runtime environment. XAML gives developers the ability to control the layout of all .NET user-interface elements such as text, buttons, graphics, and listboxes, using XML . Because XAML is XML-based, your code must be well-formed XML. Every XAML tag corresponds directly to a .NET Framework class whose properties are controlled through the use of XML attributes. For example, the <Button> tag corresponds directly to the System.Windows.Controls.Button class. XAML elements represent a Common Language Runtime (CLR) class, the runtime engine for Microsoft's .NET framework. The CLR is similar to the Java Virtual Machine (JVM), except that the JVM can only run Java language programs, while the CLR can run applications written in a number of .NET languages, such as C#, J#, and VB.NET.
Because XAML elements represent CLR objects (this book focuses on those in the Windows Presentation Foundation [WPF]), anything that can be done with XAML can also be accomplished with procedural code. There are some things, however, that can be done by manipulating the object model programmatically that are not accessible through XAML. Properties that are read-only are not exposed through XAML; only those properties that are public and have both a get and a set method are accessible to XAML developers.
Events and handlers can also be specified by XAML attributes, and the necessary code behind the handlers, codebehind
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Benefits of XAML
XAML offers similar benefits to other markup-based application interface mechanisms such as XUL (eXtensible User-interface Language), HTML (HyperText Markup Language), and Flex. Markup-based interfaces are quick to build and easily modifiable. They require less code than traditional structured programming. For example, creating and defining the properties of a Button with XAML requires just one line of syntax, as opposed to multiple lines in C# or VB.NET:
    <Button Click="OnClickHandler" Background="Green" Content="Submit" />
The same Button object created using C# requires four lines:
    Button myBtn = new Button(  );
    myBtn.Background = Brushes.Green;
    myBtn.Text="Submit";
    myBtn.Click += new System.EventHandler(OnClickHandler);
While HTML has limited programmatic functionality and control, XAML and other new-generation declarative markup languages offer back-end scripting language support to circumvent this limitation. While XAML separates the user interface from application logic, it still provides a mechanism by which the two can easily interact. This separation offers several benefits, including easily localized user interfaces and the ability for developers to modify application logic without affecting the user interface, and vice versa.
XAML also opens up user-interface design to a wider group of developers, namely graphic designers and markup developers. Anyone with experience using HTML or other web-oriented markup languages will find XAML to be intuitive; they will be able to jump in and begin developing user interfaces in a short period of time. This alleviates the burden placed on .NET developers and allows them to focus on developing application logic, while others determine the look and feel of the user interface.
XAML is toolable, which offers third-party developers opportunities to create applications that support it. Several third-party applications already exist that offer visual environments for developing XAML. Additional products are expected as Windows Vista begins to be generally deployed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What XAML Is Not
XAML is purely a markup language designed for describing user-interface components and arranging them on the screen. Though there are components of XAML that appear to be programmatic in nature, such as the Trigger and Transform elements, XAML is not a procedural programming language and is not designed to execute application logic.
XAML is interpreted, not compiled—though it can be compiled. Microsoft recommends that XAML be compiled by compacting it into Binary Application Markup Language (BAML) . Both XAML and BAML are interpreted by the WPF and then rendered on the screen in a manner similar to HTML. Unlike HTML, however, XAML is strongly typed. HTML defaults to ignoring tags and attributes it doesn't understand, while XAML requires that every tag and attribute be understood, including the typing of attributes. Although all attributes initially appear to be strings, don't let that fool you. The string represents an object, and because those objects must be understood by WPF, XAML is strongly typed.
Finally, XAML is not HTML. Although there are similarities in the declaration of elements, application of styles, and assignment of event handlers, XAML is an XML-based interface to the Windows Presentation Framework, while HTML is a markup language that is rendered within the context of the browser and operating system in which it is loaded. XAML is far more than a mechanism for displaying information and soliciting basic user input. It is a complete user-interface design and development markup language that reaches beyond the scope of simple HTML elements by including advanced features such as 3-D element rendering and rich vector-based drawing capabilities.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
XAML Development Resources
XAML can be developed in myriad ways. XAML can be written in any text editor. For example, all the code included in this book was written in Notepad and then compiled using MSBuild.
There are much easier ways to develop a XAML user interface, however, and most of them involve a visual layout tool. There are several third-party tools, as well as tools from Microsoft that support XAML. Some are focused on only one aspect of XAML, such as development of 3-D interfaces, while others are more generally applicable. Some popular tools available as of this writing include:
Electric Rain ZAM D XAML Tool (http://www.erain.com/products/zam3d/)
A tool that supports visual development of 3-D interface elements for XAML.
Xamlon Pro and XAML Converter (http://www.xamlon.com/)
Xamlon Pro supports development of XAML user interfaces in a visual environment. XAML Converter converts other formats to XAML.
MyXAML (http://www.myxaml.com/)
An open source project dedicated to XAML development. Includes a mailing list and forums focused on discussion of XAML and the sharing of tips, tricks, and techniques.
Mobiform Aurora XAML Editor (http://www.mobiform.com/2005/XAML/xamlhome.htm)
A visual editor for XAML from Mobiform.
XamlViewer (http://weblogs.asp.net/gmilano/archive/2004/11/24/269082.aspx)
A visual editor for XAML that integrates into Visual Studio 2005.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Getting Started with XAML
As with most development-oriented tools, it's important to have the proper environment before you can start developing user interfaces with XAML. This chapter discusses the prerequisites necessary to define and run XAML applications and later details the basic structure of a XAML project, as well as how to compile and run that application.
This chapter assumes that you have a working knowledge of XML and are at least somewhat familiar with other user-interface markup languages, such as ASP.NET and HTML.
Although XAML is designed specifically for Windows Vista, it's also available on Windows XP and Windows Server 2003, given that certain system requirements are met. This makes it possible for developers to become familiar with XAML and the WinFX SDK before Windows Vista is officially available.
XAML can be used to develop applications on the following operating systems:
  • Windows XP SP2
  • Windows Server 2003 SP1
  • Windows Vista
On Windows XP SP2 and Windows Server 2003 SP1, you will first need to install the WinFX runtime, which contains, among other things, the Windows Presentation Foundation (Avalon). Regardless of the operating system you choose, you'll need to install the WinFX SDK. The SDK contains the libraries, build tools, and documentation necessary to begin developing user interfaces with XAML. Depending on the operating system you choose, the WinFX SDK may also have prerequisites that must be met.
If you plan on using the WinFX Extensions to Visual Studio 2005, you must install Visual Studio 2005 before installing the WinFX SDK.
A XAML application comprises two types of elements: an application element and the set elements that make up the user interface. The XAML files contain the user-interface definition for your application. The
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
XAML Prerequisites
Although XAML is designed specifically for Windows Vista, it's also available on Windows XP and Windows Server 2003, given that certain system requirements are met. This makes it possible for developers to become familiar with XAML and the WinFX SDK before Windows Vista is officially available.
XAML can be used to develop applications on the following operating systems:
  • Windows XP SP2
  • Windows Server 2003 SP1
  • Windows Vista
On Windows XP SP2 and Windows Server 2003 SP1, you will first need to install the WinFX runtime, which contains, among other things, the Windows Presentation Foundation (Avalon). Regardless of the operating system you choose, you'll need to install the WinFX SDK. The SDK contains the libraries, build tools, and documentation necessary to begin developing user interfaces with XAML. Depending on the operating system you choose, the WinFX SDK may also have prerequisites that must be met.
If you plan on using the WinFX Extensions to Visual Studio 2005, you must install Visual Studio 2005 before installing the WinFX SDK.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Defining XAML Applications
A XAML application comprises two types of elements: an application element and the set elements that make up the user interface. The XAML files contain the user-interface definition for your application. The codebehind files will contain the application logic and the code that handles event processing. XAML does not provide a mechanism for handling events, but it can direct the runtime engine to call event handlers written in C# or VB.NET. If you're a developer, you'll code the event handlers and application logic just as you always have, but because the user-interface code is separate, you'll have to pay a bit more attention to the names of the handlers and elements you reference because you don't define them—they're declared and named in the XAML file.
You can define XAML applications completely using C# or VB.NET. The CLR classes represented by XAML are all accessible through code, and you can write applications just as you always have, if you so desire. XAML offers you the ability to completely separate the presentation layer (user interface) from the application logic, thus making it easier to split up development responsibilities and isolate UI changes from the code. Appendix H provides an example of an application declared in XAML, as well as entirely in C#.
The most common application element is of type NavigationApplication. NavigationApplication defines an application that behaves like a web application or wizard in that it consists of pages between which a user navigates using hyperlinks and forward and back buttons.
The application definition is generally declared in its own file. It requires two properties to be set, the namespace and the startup URI, which is the URI of the first page that should be loaded when the application starts. For our purposes in this chapter, the application definition file will be called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Building XAML Applications
While XAML can be used to create libraries and modules that can be shared and used to build other applications (in the same way that C# or VB.NET can be used to build DLLs or shared assemblies), it is more likely that you will use XAML to generate an application. There are two types of XAML applications: express and installed. Express applications are hosted in a web browser. Installed applications are traditional desktop applications and can be either Windows applications or console applications. The type of application generated is determined by a property value in the project file MSBuild uses to assemble the application.
MSBuild is one of the new features in Windows Vista and Visual Studio 2005. With the release of Visual Studio 2005, Microsoft has moved to a unified build environment. All projects now use MSBuild facilities to generate CLR assemblies. The most exciting, and beneficial, aspect of this change is that Visual Studio is no longer required to compile and build applications; builds can be completely automated without it. MSBuild is distributed with the WinFX SDK.
If you're using Visual Studio to edit XAML and associated codebehind files, don't worry about the details of MSBuild. The relevant files are generated automatically by Visual Studio.
MSBuild is similar to ANT and Unix/Linux make facilities. MSBuild reads in XML-based project files, conventionally named with a .proj extension, and executes the tasks contained in the project file to produce the desired target.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
XAML Applications and Visual Studio
Working in Visual Studio, you'll be able to select a number of WinFX Applications, and the project files and application manifest will be generated automatically. You can choose to create a WinFX Windows executable, a WinFX WebBrowser application, a WinFX Service Library (which creates a WinFX library comprising the definition and implementation of a WinFX Service), or a WinFX Custom Control Library (for extending WinFX controls). However, you'll still have to edit both the XAML and associated C# or VB.NET codebehind files manually.
If you've downloaded and installed the WinFX extensions for Visual Studio 2005, fire up the IDE. Choose Create Project and you'll be presented with a list of options, as illustrated in Figure 2-3.
Figure 2-3: WinFX application options in Visual Studio 2005
To create an application, choose either WinFX Windows Application or WinFX WebBrowser Application, depending on whether you want to deploy the application as an executable or for use within a web browser. Give the project a name and click OK. Visual Studio automatically generates the default XAML and codebehind files. In Figure 2-4, you can see that it has generated Windows1.xaml (Example 2-5) and Windows1.xaml.cs (Example 2-6). The language of the codebehind file depends on your choice of .NET-supported languages. I have chosen C#, so the generated files will reflect that choice.
Figure 2-4: Default files generated by Visual C# 2005 Express Edition
There are some minor differences between creating a WinFX WebBrowser and WinFX Windows application that occur whether or not you use Visual Studio. In a WebBrowser application, the default start page's root element is
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: The Basics of XAML
XAML is an XML-based markup language. Given that, it shares many properties with other XML documents, such as case sensitivity and having to be well-formed. XAML has some specific syntax peculiarities designed for easing the declaration of specific types of elements. It provides abbreviated markup syntax for specific types of elements that take advantage of the underlying Common Language Runtime (CLR) class constructors.
This chapter will examine the core XAML syntax, as well as some of the peculiarities of its abbreviated markup syntax, in preparation for understanding more complex concepts in later chapters.
XAML generally follows XML syntax rules, just as any other XML-based markup language does. Each XAML element has a name and one or more attributes. Attributes correspond directly to object properties, and the name of the XAML element exactly matches the name of a CLR class definition.
XAML is pure markup, which means that while the names of event handlers are specified as attributes, you must implement the actual logic of the event handler in code. If you're familiar with ASP.NET programming techniques, then you'll be familiar with the term codebehind, which refers to the code "behind" a XAML interface element that is responsible for providing application logic such as event handlers. It can be implemented in either C# or VB.NET. In both cases, the code can be placed inline in the XAML file, although this contradicts best practices in separating the presentation and application logic layers.
How does this work? Every event in XAML can be assigned to a codebehind handler, which is implemented in a supported .NET language. For example, it's a common task to do something when a Button is clicked. So, first a Button is declared with the XAML code shown in Example 3-1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Core XAML Syntax
XAML generally follows XML syntax rules, just as any other XML-based markup language does. Each XAML element has a name and one or more attributes. Attributes correspond directly to object properties, and the name of the XAML element exactly matches the name of a CLR class definition.
XAML is pure markup, which means that while the names of event handlers are specified as attributes, you must implement the actual logic of the event handler in code. If you're familiar with ASP.NET programming techniques, then you'll be familiar with the term codebehind, which refers to the code "behind" a XAML interface element that is responsible for providing application logic such as event handlers. It can be implemented in either C# or VB.NET. In both cases, the code can be placed inline in the XAML file, although this contradicts best practices in separating the presentation and application logic layers.
How does this work? Every event in XAML can be assigned to a codebehind handler, which is implemented in a supported .NET language. For example, it's a common task to do something when a Button is clicked. So, first a Button is declared with the XAML code shown in Example 3-1.
Example 3-1. XAML Button declaration
    <Button
        OnClick="ButtonClickedHandler"
        Name="MyButton"
        Width="50"
        Content="Click Me!" />
Then, a corresponding codebehind handler is declared, and, when the Button is clicked, the handler is automatically executed (Examples 3-2 and 3-3).
Example 3-2. Button OnClick handler in C#
    void ButtonClickedHandler(object sender, RoutedEventArgs eventArgs)
    {
          MyButton.Width = 100;
          MyButton.Content = "Thank you!";
    }
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Elements
All XAML elements are an XML representation of CLR classes, but not all CLR classes are represented in XAML. Most of those represented are user-interface elements and are ultimately derived from System.Windows.UIElement, which provides basic visual user-interface properties that are shared by most XAML elements . A System.Windows.UIElement can render itself, receive input via the keyboard and mouse, visually size and position its child elements, and raise events.
Not all XAML elements are derived from System.Windows.UIElement. Some, such as LineBreak, TableColumn, and Document, are derived from System.Windows.Frame-workContentElement. System.Windows.FrameworkContentElement elements cannot render themselves but are instead rendered by another class, usually the container in which they have been placed.
Most XAML elements can be organized into five basic categories:
  • Root elements
  • Control elements
  • Panel elements
  • Shape and geometric elements
  • Document elements
Root elements function as the page's base container for all user-interface elements. A page is required to have one root element. The most commonly used root elements are the panel elements—StackPanel, DockPanel, Canvas, and Grid—and Page, a root element that allows you to declaratively control a number of the properties of the window containing the XAML page. To be considered a root element, the element must be a container for at least one other element. (When displaying XAML output in XamlPad, you don't have to include a root element because XamlPad provides it on your behalf.) You can create custom root elements by deriving new classes from Page or Window and exposing them as XAML elements.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Attributes
Attributes are the XML representation of the properties of an element's corresponding CLR class. The Width attribute of the XAML Button element corresponds directly to the Width property of the System.Windows.Button class. To show the correlation between XAML and CLR classes, Examples 3-7 and 3-8 declare a Button instance and its attributes in both XAML and C#.
Example 3-7. Button declared in XAML
    <Button
         Width="100"
         Name="myButton"
         Height="20"
         Content="This is my button" />
Example 3-8. Button declared in C#
    Button myButton;
    myButton.Width=100;
    myButton.Height=20;
    myButton.Content = "This is my button";
As with the XAML tags for elements, attributes are spelled exactly the same as their corresponding CLR class properties. (Width = Width, Content = Content . . . You get the picture.)
There are two types of XAML attributes. The first, dependency properties, are public static read-only fields on CLR classes that are derived from DependencyProperty and have declared CLR accessor methods. In other words, the value of dependency properties can be dependent on (hence the name) other variables in CLR classes and, therefore, can only be accessed with a public get or set accessor method to be evaluated properly.
Dependency properties are like stock certificates. The stock certificate represents a value (money), but the actual amount of money it is worth (its value) is determined by external calculations and can change at nearly any time. To determine the value of your stock certificate, you must consult the stock exchange and do some multiplication. Dependency properties can also be based on external resources and often rely on calculations to determine their value.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Attached Properties
A few XAML elements have attributes that are declared in other elements rather than in the element itself. These attributes are called attached properties . Attached properties are generally used to position elements within a parent element. Two elements with attached properties are Grid and DockPanel. Grid uses attached properties to describe the row and column in which an element should be contained. DockPanel uses attached properties to describe the location within the panel where an element should be placed.
Attached properties can be set on any element that derives from DependencyObject. UIElement derives from DependencyObject, so the requirement is met by most XAML elements.
Attached properties are declared in an element by using a reference to the element and the attribute being declared in the following manner: AttachPropertyProvider.PropertyName . For example, Grid has two attached properties: Row and Column. An element contained within a specific row/column combination in a grid would specify the row as an attribute with the name Grid.Row and the column similarly as Grid.Column. Example 3-14 describes the use of these attached properties.
Example 3-14. Using the attached properties of Grid
    <Grid
        ShowGridLines="true">
        <ColumnDefinition
             Width="50"/>
        <ColumnDefinition
             Width="50"/>
        <RowDefinition
             Height="100" />
        <RowDefinition
             Height="25" />
        <RowDefinition
             Height="25" />
        <TextBlock
             Grid.Column="0"
             Grid.Row="0">Col 0, Row 0
        </TextBlock>
        <TextBlock
             Grid.Column="1"
             Grid.Row="0">Col 1, Row 0
        </TextBlock>
        <TextBlock
             Grid.Column="0"
             Grid.Row="1">Col 0, Row 1
        </TextBlock>
        <TextBlock
             Grid.Column="1"
             Grid.Row="1">Col 1, Row 1
        </TextBlock>
    </Grid>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Binding Properties
Another mechanism in XAML that can be used to declare the value of attributes is a bind declaration . A bind declaration allows you to set an attribute's value by referencing the value of another element. Bind declarations must be attached to a specific dependency property of a target element. Remember that dependency properties are static read-only properties of a CLR class that are exposed only through get and set accessor methods to support concepts such as binding. Properties are bound together in a bind declaration using the Binding element.
Binding elements are used to bind the source to target elements. If the dependency properties in the source elements change when the application runs, the dependency properties in the target elements will change as well. Basically, you're telling an attribute that its value should always be determined by evaluating some other attribute or data source. It's like assigning a value to one variable by assigning it to another, as shown in the following example:
    int a = 1;
    int b;
    b = a;
The difference between code-based variable assignments and XAML binding is that in XAML, the association is permanent. The assignment of b = a in the code example happens only once, and, if a changes later, b doesn't follow suit. In XAML, the Binding keyword ties the values together permanently.
The syntax for a Binding element is as follows:
    <ElementName Attribute="{Binding Path=SimpleProperty, Mode=OneTime} />
The curly braces are a general indicator to the parser that the value contained in the braces is not a simple value. Instead, the first keyword within the braces indicates the type of special handling needed. The Binding statement at the beginning of the string indicates a binding declaration.
An example of how binding works is when you are tying together the content of two different elements, such as a Button and a TextBlock. In Example 3-15, every time the Button is clicked, the C# code (Example 3-16) in its
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
codebehind
The concept of codebehind has been mentioned but not fully explored yet. You've already noted that event handlers can be assigned to elements and implemented in code and that the attribute name must exactly match the handler name in code. The event handlers specified by name as attributes for controls are associated with the codebehind in a C# or VB.NET file during the compilation process. The compiler generates a partial class for XAML and then assembles it with the code, which defines the rest of the class in a codebehind file. This allows the two pieces to be tied together when the code is interpreted within the runtime engine.
But there are other things that can be accomplished in code besides handling events. Many applications require initialization of data sources, or automatically adding fields to the user interface depending on the user's role. These things cannot be done in XAML; they must be done programmatically.
Every XAML application represents the declaration of a partial CLR class. Part of the class is declared using XAML, and the rest of it can be declared in a codebehind file using C# or Visual Basic. The implementation can then programmatically modify the user interface or interact with other systems such as a database or remote application to accomplish the application's designated task.
As with event handlers, the name of the class assigned as the implementation class for a XAML application must exactly match, including the namespace. For example, the XAML class declaration in Example 3-18 referencing the StartPage class with a namespace of MyNameSpace exactly matches the name of the class in Example 3-19. Note that the Page element in the XAML file has no other elements. The TextBlock and Button seen in Figure 3-7 are the result of programmatically adding the two elements to the Page in the C# codebehind implementation.
Example 3-18. XAML declaration of StartPage.xaml
    <Page xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
          xmlns:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Layout and Positioning
One of the most important facets of user-interface design is the layout and positioning of elements on the page. The user interface must be pleasing to the eye without being cluttered, and it must enhance productivity through ease of use. Elements should be paired with visual clues such that their use is intuitive, which reduces the amount of learning time required.
One of the primary mechanisms for building an intuitive, usable user interface is layout elements. Layout elements position elements on the screen and insure that they are grouped together in a way that enhances readability. XAML offers a plethora of options for page layout and user-interface construction. Margins, padding, and panels provide basic layout capabilities that can be combined to position elements exactly where you want them on the page.
The largest hurdle to building a user-interface layout is the variation in screen resolution and size among end users. This is especially true for applications loaded in a web browser. There are several mechanisms available through scripting and CSS to counter the layout problems inherent in serving a wide variety of screen resolutions and sizes .
XAML addresses these issues by dynamically sizing elements relative to the size of the page in which they are placed. All XAML elements will stretch to fit their entire container, unless you indicate otherwise. If the default container is a page 800 pixels wide, then all elements added to the page will size themselves to be 800 pixels wide. Similarly, if the page is resized, the elements will dynamically resize themselves to fit the page.
While this resizing behavior is needed to handle varying window sizes, it isn't necessary for elements to take up the entire screen. This chapter examines the XAML elements and attributes that control the layout and size of elements on the page while maintaining the flexibility that dynamic sizing offers.
The two most commonly used
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
StackPanel and DockPanel
The two most commonly used Panel subclasses are StackPanel and DockPanel. Both are used for relative positioning of elements and automatically handle placement of elements based on the order in which they are declared.
The differences between the two types of Panel can be summed up as follows:
StackPanel
Defaults to automatically rendering elements in the order in which they are declared in the XAML file, from top to bottom.
DockPanel
Defaults to automatically rendering elements in the order in which they are declared in the XAML file, from left to right.
The attached attributes of DockPanel can be used to alter the relative positioning of child elements.
The concept is best illustrated by recreating the user login interface (from Chapter 3) using both types of panels. The result is shown in Figure 4-1. The elements of this user login interface are each added in the following order:
  1. The Username Label element
  2. The username TextBox
  3. The Password Label element
  4. The password PasswordBox
  5. The Submit Button element
Figure 4-1: Positioning elements with StackPanel and DockPanel
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Width and Alignment
By default, XAML renders elements on the screen in the order in which they are defined within the XAML file. If the TextBox in Example 4-2 is added to the StackPanel before the first Label, then it will appear as the first element and the Label will appear after it. By default, all elements have a width equal to the container element of which they are children. Using the login page example from Chapter 3 without specifying any kind of formatting or layout restrictions yields the user interface in Figure 4-6.
Figure 4-5: Using DockPanel.Dock to position elements
Example 4-2. Example code for user login screen with no layout or formatting
<Page
    xmlns="http://schemas.microsoft.com/winfx/avalon/2005">
    <StackPanel 
>
        <Label>Username</Label>
        <TextBox>username@example.com</TextBox>
        <Label>Password</Label>
        <PasswordBox></PasswordBox>
        <Button Content="Submit" />
    </StackPanel>
</Page>
This is neither aesthetically pleasing nor is it particularly usable. There is no clear delineation between elements, and it is hard on the eyes. The first thing to do is limit the width of the elements to make them easier to read. There are three options to accomplish this: define the Width attribute on all the elements added to the StackPanel, limit the width of the StackPanel itself, or change the HorizontalAlignment of the StackPanel. The second option will force all the elements in the StackPanel to be the same width. While this is a viable option, it may not be appropriate for every situation, especially if you don't want all the elements to be the same width as the TextBox. The best option in this case is to limit the width of each individual element. Note that specifying the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Margins and Padding
If you're familiar at all with CSS, then you're familiar with the concept of padding and margins. Padding and margins assist user-interface designers in positioning elements and content in elements. The two attributes are both described by a Thickness element but serve different purposes in layout.
Margin describes the distance between the element and its children or peers. It is used to position elements relative to other elements. Using abbreviated markup syntax, you can specify its thickness as a uniform distance around the element, e.g., Margin=" 20 ", or as the distance in each individual direction in terms of left, top, right, and bottom (in that order), e.g., Margin=" 20 , 10 , 20 , 10 ".
Margin is one of the elements that does not require commas in its abbreviated markup. It can be described using either comma- or space-separated values.
Specifying a Margin value on the StackPanel in our user-login example will only change the distance between the StackPanel and the edges of the Page. To illustrate the concept of Margin, examine Figure 4-10. A second StackPanel has been added, containing the same elements for the user-login interface as well as borders to illustrate the Margin property at work. (In order to produce a side-by-side comparison of two StackPanel elements, both were enclosed in a DockPanel.) The black-bordered StackPanel has no Margin at all, while the lighter-bordered StackPanel has a uniform Margin of 20 device-independent pixels. You can see the difference in the positioning of the elements in relation to their children. The
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Grid
The Grid element is useful for relative, automatic positioning strategies in which some control over element placement is required. Grid is similar to Table (just like the HTML Table) and provides individual cells in which elements can be positioned. Grid is more complex than Table, however, and should not be treated as a simple Table element. Grid cell sizes can be explicitly declared as a number of device-independent pixels, as a percentage of the overall available Width and Height, or as auto-size factors based on their content by using the enumeration Auto.
Grid, like DockPanel, uses attached attributes to position child elements. Grid uses two attached attributes, Row and Column, to determine placement of child elements within its cells.
Grid uses zero-based indexing when specifying Row and Column placement.
A sample Grid might appear as follows:
Column 0, Row 0
Column 1, Row 0
Column 2, Row 0
Column 0, Row 1
Column 1, Row 1
Column 2, Row 1
To add elements to the Grid, specify which row and column the element is being added to. For example, to add an element to the cell in Column 1, Row 1, you would declare the element like this:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Absolute Positioning
Thus far, StackPanel, DockPanel, and Grid elements have been used to position elements on the Page. Positioning with these Panel elements is a purely relative positioning strategy and offers no control over the x- and y-coordinate values of the element's position. Like CSS, relative positioning is used to allow elements to flow and reposition in the event that the page size changes. There are times, however, when absolute positioning is desired. XAML supports absolute positioning through the use of the Canvas element.
All elements on a Canvas element must be absolutely positioned or they will stack on top of one another. Absolute positioning is accomplished using the attached attributes of Canvas, namely Top, Left, Bottom, and Right.
If specified, the attached attributes Top or Left take priority over Bottom or Right.
The coordinate system used to position elements places 0,0 in the upper-left corner of the Canvas. Values specified for Top, Left, Bottom, and Right are relative to the Canvas, not the Page. If the Page contains only a single Canvas, then the value is relative to both, but only because the Canvas ends up positioned with 0,0 in the same place as 0,0 on the Page.
So, absolute positioning is actually relative, in an absolute kind of way. An example is probably in order after that mouthful. Figure 4-13 shows the relativity of absolute positioning. A Canvas has been added to a Canvas, specifying Top and Left values of 100 and 200, respectively. The unboxed coordinates are Label elements added to the parent Canvas, while the boxed coordinates are those added to the second Canvas. The Labels were added with the same Top and Left coordinates, but you can see that the Labels added to the second (the child) Canvas are offset. The code producing Figure 4-13 is shown in Example 4-6.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Resources
Every XAML element has a collection of resources . Resources provide a mechanism for defining common styles or elements that can be reused throughout the user interface. They also configure the actions that are carried out when a user interacts with a display element.
The benefit of using resources to define reusable, common styles is that modifications can be applied to one element, but they will take effect throughout the entire application. This reduces the chance of error and the possibility that an element might be missed when changes are applied. For example, you may want to define a specific Point from which all geometric shapes will originate. By defining the Point as a resource and referencing it as the appropriate attribute value of geometric elements, the origination point can easily be changed in one place—the resource declaration—without concern for mistakes made in multiple places throughout the user interface.
Local resources are defined on the element, while global resources are defined on the root element. Global resources can be used by all elements in the page while local resources are reserved for use by the element in which they are declared. Regardless of the type of resource (local or global), the syntax used to declare the resources is the same.
Although every element has a collection of resources, they are usually declared only on the root element.
When adding resources, you must add the appropriate namespace to the root element. You'll also need to give it a name to differentiate it from the default namespace. The default namespace, which references Avalon, contains the definitions of Avalon elements, such as Button, Page, and StackPanel. The namespace that must be added to define resources is the XAML namespace and describes the language itself.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Using Resources
When adding resources, you must add the appropriate namespace to the root element. You'll also need to give it a name to differentiate it from the default namespace. The default namespace, which references Avalon, contains the definitions of Avalon elements, such as Button, Page, and StackPanel. The namespace that must be added to define resources is the XAML namespace and describes the language itself.
Because resource definitions require the use of XAML-specific tags—which are not described by the default namespace—you must declare a reference to the XAML namespace and use it to prefix those attributes found only there, such as Key.
The key is a fully qualified attribute comprising the namespace, a colon, and the keyword K