Cover | Table of Contents
<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.get and a set method are accessible to XAML developers.codebehindButton 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" />
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);
Trigger and Transform elements, XAML is not a procedural programming language and is not designed to execute application logic.http://www.erain.com/products/zam3d/)http://www.xamlon.com/)http://www.myxaml.com/)http://www.mobiform.com/2005/XAML/xamlhome.htm)http://weblogs.asp.net/gmilano/archive/2004/11/24/269082.aspx)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.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.codebehind files, don't worry about the details of MSBuild. The relevant files are generated automatically by Visual Studio.codebehind files manually.
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.
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.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.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.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.
<Button
OnClick="ButtonClickedHandler"
Name="MyButton"
Width="50"
Content="Click Me!" />
codebehind handler is declared, and, when the Button is clicked, the handler is automatically executed (Examples 3-2 and 3-3).
void ButtonClickedHandler(object sender, RoutedEventArgs eventArgs)
{
MyButton.Width = 100;
MyButton.Content = "Thank you!";
}
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.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.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.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#.
<Button
Width="100"
Name="myButton"
Height="20"
Content="This is my button" />
Button myButton;
myButton.Width=100;
myButton.Height=20;
myButton.Content = "This is my button";
Width = Width, Content = Content . . . You get the picture.)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.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.DependencyObject. UIElement derives from DependencyObject, so the requirement is met by most XAML elements.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.
<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>
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;
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.Binding element is as follows:
<ElementName Attribute="{Binding Path=SimpleProperty, Mode=OneTime} />
Binding statement at the beginning of the string indicates a binding declaration.Button and a TextBlock. In Example 3-15, every time the Button is clicked, the C# code (Example 3-16) in its 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.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.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.
<Page xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
xmlns: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.Panel can be summed up as follows:StackPanel
DockPanel
DockPanel can be used to alter the relative positioning of child elements.Label elementTextBox
Label elementPasswordBox
Button element
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.
<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>
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 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.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 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.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
|
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: 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.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.Top or Left take priority over Bottom or Right.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.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.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.Button, Page, and StackPanel. The namespace that must be added to define resources
is the XAML namespace and describes the language itself.Button, Page, and StackPanel. The namespace that must be added to define resources
is the XAML namespace and describes the language itself.Key.Key. Elements defined as a resource must have a declared "key name" to be referenced by other elements. The value of the attribute is the name by which the resource will be referenced by other elements.Resources attribute of an element.SolidColorBrush defined as resources: RedBrush and BlueBrush.
<Page
xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005"
<Page.Resources>
<SolidColorBrush
x:Key="RedBrush"
Color="red"/>
<SolidColorBrush
x:Key="BlueBrush"
Color="blue"/>
</Page.Resources>
<StackPanel>
<Button
Background="{StaticResource RedBrush}" />
<Ellipse
Fill="{StaticResource BlueBrush}"
Margin="40"
Width="15"
Height="Style is a set of properties applied to an element that can be used to describe the appearance of an element. It is used in a similar manner as styles declared in CSS. A style can be applied locally to a single element, or it can be declared globally and referenced from the element. Styles can also be declared such that they affect all instances of a given type, such as Button.Style is a collection of one or more Setter elements that act upon a specified dependency property, such as Background or Foreground. Remember that a Key value is required if the style will be applied by reference to an element. In Example 5-4, the Style
MyStyle is declared as the value of the Style element on the Button, which sets the background, foreground, and width attributes to the values specified by the Style declaration.
<Page
xmlns="http://schemas.microsoft.com/winfx/avalon/2005"
xmlns:x="http://schemas.microsoft.com/winfx/xaml/2005">
<Page.Resources>
<Style
x:Key="MyStyle">
<Setter
Property="Control.Background"
Value="Red" />
<Setter
Property="Control.Foreground"
Value="White" />
<Setter
Property="Control.Width"
Value="100" />
</Style>
</Page.Resources>
<StackPanel>
<Button
Style="{StaticResource MyStyle}"
Content="A Red Button"/>
</StackPanel>
</Page>