Wednesday, February 16, 2011

WPF in Visual Studio

Windows Presentation Foundation (WPF) is a .NET technology for building desktop
applications. The result of building a WPF application is an *.exe file that you can
run directly on your computer or deploy and run on any other computer that has .NET
installed. With WPF, you can add a graphical user interface (GUI), pronounced "Gooey,"
that makes it easier for users to work with your program.
This Article will show you how to lay out a screen in WPF and explain the controls, such
as Button and TextBox, that you can place on the screen. You'll also learn how to capture
events off controls, allowing you to add code that runs based on user input. Since most
applications work with data, this Articlebuilds on what you learned in C#, OOPS concepts
and shows how to bind data to controls in the GUI.
This Article will show you how to build a WPF GUI with the VS Designer, but
sometimes you must work at a lower level and manipulate the XAML, pronounced
"Zammel," that defines the GUI. XAML is an XML format that WPF and Silverlight
use to define a GUI. There are two Article in this blog that will help you get up to
speed in XAML: Article 1, "XML in Visual Studio" and Article 2, " XAML in WPF and
Silverlight." If you aren't familiar with XML, start with Article 1. However, if you have
a good grasp of basic XML syntax, go straight to Article 2. I'll try to explain WPF in
a way that any XAML you see can be understood in its context, but you might want to
review the Articles to avoid any confusion. Once you're familiar with XAML, you can
return here and start with the next section, which explains how to start a WPF project.
Starting a WPF Project
May be you know that how to create and build projects. The example explained how
to create a Console application. However, what you learned there is generally applicable
to most other application types. This section builds upon what you already know about
projects and explains what is unique to a WPF application. To get started, open the New
Project window; select WPF Application; and fill in the project name, location, and
solution name. I'm naming the examples in the chapter as MyShop to continue the idea
of customers who buy products. Figure 1 shows the new WPF application in VS, including
a Toolbox, a Designer, and a Solution Explorer. The Toolbox contains controls, which are
user interface (UI) elements, such as Button and Textbox, that you can drag and drop onto
the Designer.

NOTE
There is another .NET technology, Windows Forms, for creating desktop applications.
This book doesn't discuss Windows Forms because it's an older technology. The way
forward for desktop application development is WPF, and the intention of this book is to
help guide you in a direction most beneficial to you.

The Designer allows you to lay out the UI of the application; it is divided into Design
on the top and XAML on the bottom. The Design surface allows you to visually work
with controls and layouts of those controls. The XAML editor allows you to work with
the XML representation of the controls on the design surface. The Design and XAML are
interrelated because a change in one causes a change in the other. For example, if you add
a Button to the Design, you'll see the XML representation of that Button in the XAML.
Figure 1  new WPF application project
 
Understanding Layout
A layout defines how you can position and size controls on a screen. WPF windows and
controls have a Content (can occasionally be called something else) property that accepts
a single control. In some cases, such as a Button control, the content can be text. However,
many situations call for the ability to lay out multiple controls. This section concentrates
on performing layout in windows, and a Window has a Content property that accepts
only one control; that one control should be a layout control, which is the subject of this
section.
WPF includes several layout controls, including Grid, StackPanel, DockPanel,
WrapPanel, and Canvas. By default, VS will generate a window with a Grid as the layout
control. However, you are free to replace the Grid with any other layout control that suits
your needs. This section will show you how to use each of these controls.
Grid Layout
Whenever starting a new WPF project, VS adds a Grid. A Grid is a layout control that
allows you to create a set of rows and columns that hold other controls. You can add rows
and columns to a Grid through the Visual Designer by clicking in the middle of a window
in design view. Figure 2 shows a column being added to a Grid.
The thin vertical line in the middle of the window is a new border between two columns.
After clicking the window, you'll see two thick borders on the left and top of the window.
While you hover over the top border, VS draws a vertical line that moves left and right as
you run your mouse along the top border. You can do the same with the left border, adding
rows to the Grid. This is a very quick way to add rows and columns to a Grid.
Figure 2 Adding columns and rows to a Grid
The arrow in the Grid border allows you to reposition the column or row border.
You can remove the column or row border by selecting the arrow in the Grid border and
dragging the arrow off the window.
CAUTION
Don't press the DELETE key when you have a border selected. You'll accidentally delete
your Grid, which you might have spent some time on. If you want to remove a column
or row, grab the arrow for the border you want to remove and drag the border off the
window.
Once you've created rows and columns, you can add further customizations that
define how much space the column or row can take. There are three sizing customizations:
fixed, weighted, and auto. To set each of these options, hover over the column or row
border and VS will display a sizing panel, as shown over the left column design border in
Figure 3.
The diamond icon on the left means fixed, where the size will stay the same. The asterisk
icon in the middle is a weighted proportion, where the size stays the same in relation to
the other columns. The rightmost icon is auto, meaning that the size will vary according to
Figure 3 Column and row sizing options

whatever space remains after the other columns' sizes are set. After you've added content to
your Grid, you can use these sizing options to experiment with the layout that you want.
One thing to notice in Figure 8-3 is the number in the Grid border for each row and
column. These numbers tell you the size in pixels for each row and column they appear
upon.
Figure 3 also shows the Properties window on the right, where you can select and
customize the Column and Row collections.
True to the purpose of the Grid, Figure 3 shows controls that have been added to
the Grid, placed in each cell of the Grid. Another popular layout control is StackPanel,
discussed next.
StackPanel Layout
The StackPanel is ideal for when you want to lay out controls each on top of the other, like
a stack. You can use a StackPanel by dragging the StackPanel control from the Toolbox
onto the design surface. If you want to use the StackPanel as your primary layout, you can
Figure 4 Using a StackPanel layout
select the grid, which is added by default to a new project, and delete the Grid. Figure 4
shows a StackPanel that contains multiple button controls.
In Figure 4, it doesn't matter where you try to lay the buttons—the StackPanel will
always lay them out one after the other. In addition to vertical layout, the StackPanel can
lay out controls horizontally. Just change the Orientation property, shown in the Properties
window in Figure 4, to Horizontal. Next, you'll learn how to dock controls to the sides
of a container.
DockPanel Layout
You've seen how VS allows you to dock windows within the borders of the application.
This helps you organize your screen so that you can use many tools at one time. You can
lay out your controls the same way with the DockPanel control.
Get started by dragging and dropping a DockPanel control from the Toolbox to the
Window in the design surface. You might want to delete the default Grid first. Also, the
DockPanel initializes with a Height and a Width, which you'll probably want to remove
by selecting the DockPanel, opening the Properties window, and clearing the Height and
Figure 5 DockPanel layout
 Width properties. Removing the Height and Width properties allows the DockPanel to
expand and cover the entire window. Figure 5 shows a DockPanel with Label controls in
each docking position.
Every time you drag and drop a control onto the design surface of a DockPanel, the
control will take the center position by default. To specify where the control should dock,
open the Properties window and set the DockLayout.Dock property. When you add a new
control, the new control will become the center control and the other control will dock to
the side of the DockPanel you specified in the Dock property. The next layout control is
WrapPanel.
WrapPanel Layout
Whenever controls should naturally follow each other in sequence and continue wrapping
on new lines, you can use a WrapPanel. Examples of when this is useful could be when
adding controls that contain text and it's useful to view the controls in sequence. Figure 6
shows several CheckBox controls in a WrapPanel.
Figure 6 The WrapPanel Layout control
Figure 6 demonstrates how you can lay out a group of controls to fill an available
space. In the case of the CheckBox controls, the Orientation of the WrapPanel is set to
Vertical (the default is Horizontal). When the number of CheckBox controls fills the
vertical column, remaining CheckBoxes wrap to the next column. Because the sizes of the
CheckBox controls are the same, you have a uniform layout, which is easier than trying
to do the same thing with a Grid or other layout control. The final layout control we'll
discuss is the Canvas, which is next.
Canvas Layout
There are times when you might want to perform explicit layout of controls. If you
were building a diagramming application or a drawing program, or if you just wanted to
explicitly specify the location of controls, the Canvas layout will work fine. Figure 7
shows some controls on a Canvas layout.
The Rectangle and Ellipse controls were dragged and dropped from the Toolbox onto
the Canvas control. Notice the Canvas.Left, Canvas.Top, Width, and Height properties in the
Properties window, demonstrating the absolute positioning of the selected Ellipse control.


Figure 7 The Canvas Layout control
Now that you know how to use the layout controls, the next section takes a closer look
at WPF controls in general, giving you tips on how to use them in your application.
Using WPF Controls
WPF includes many controls for helping you build user interfaces. This section groups
the controls into categories, including text, selection, containers, information, shapes, and
decorators. Data controls are excluded on purpose because the section following controls
is "Working with Data in WPF." Before diving into each control, let's do an overview of
the VS environment associated with control work.
Managing Windows for Controls
When working with controls, you'll be working with four different windows: Toolbox,
Solution Explorer, Designer, and Properties. You learned how to access each of these
windows in earlier chapters; but as a convenience, Table 8-1 gives you a quick summary
on how to open these windows.
Window                                  Menu                                                                     Keystroke
Toolbox                            View | Toolbox                                                            CTRL-W, X
Solution Explorer             View | Solution Explorer                                             CTRL-W, L
Designer                          Double-click *.xaml file in Solution Explorer               SHIFT-F7
Properties Window          View | Properties window                                           CTRL-W, P
Table 1 Primary Windows for Working with Controls
You'll find all of the available controls on the Toolbox, divided into panels where the
top panel is Common WPF controls, which makes it easy to find the controls you use the
most. The All WPF Controls tab includes the complete list of WPF controls.
You've seen how the Designer can be used in the preceding section, which discussed
layout controls. You can open the Designer by double-clicking a *.xaml file in Solution
Explorer. To add a control to the Designer, select the control in the Toolbox and drag the
control onto the Designer. Figure 8 shows a Button that has been dragged and dropped
onto the Designer.


Figure 8 Adding a control to the VS Designer
 In Figure 8, you can see the Toolbox with the Button control selected. The Designer
shows a Button control that has been dragged and dropped. In practice, you'll be adding
this control into some type of layout control so that you can position it appropriately on
the screen.
Below the Designer, the Button control appears in the XAML for this window. If
you are uncomfortable looking at XAML, you can review XAML Article as a refresher.
The attributes of the Button control in the XAML match the properties in the Properties
window.

TIP
It's important to learn how to quickly build UIs using the Visual Designer because
it enhances productivity. However, it's also important to be able to read the XAML
associated with a window because as you move beyond the beginner content of this
book, you'll find scenarios where the Designer alone might not allow you to control
every nuance of your visual presentation. A good way to move forward is to experiment
on your own by adding each of the controls from the Toolbox to the Designer and then
examine the generated XAML.

Setting Properties
The Properties window shows all of the ways that you can configure a control. For button
controls, you'll want to change the Content property to make the text on the button make
sense. In this example, we'll imagine that the purpose of the button is to allow a user to
create a new order for a customer. Therefore, set the Content property to New Order.
Handling Events
In addition to properties, you can handle control events via the Events tab at the top of the
Properties window. Figure 9 shows the contents of the Events tab.
Controls have literally dozens of events that allow you to manage their behavior in the
application. Some events, like Click, are commonly used, while other events, such as Drag
Over, only support unique scenarios like drag and drop that you might not ever care about.
To handle an event, you can double-click any of the events in the Properties window and
VS will wire up that event to a handler method with a default name.
Since the Click event is so common, I'll show how it works. You can implement a
handler for the Click event by double-clicking the Click event in the Properties window
Events tab. When you double-click, VS opens a file named MainWindow.xaml.cs,
assuming the window you're working with is named MainWindow.xaml. MainWindow
.xaml.cs is called a code-behind file and is where you can add event handlers. VS also
creates a skeleton method in MainWindow.xaml.cs that handles the Button Click event,
shown in Listing 1.
    
Figure 9 The Properties window Events tab

TIP
Controls have default events. The significance of default events is that if you double-click
the control in the Designer, VS will generate an event handler for the default event. To
be more specific, consider the Button control whose default event is the Click event. If
you double-click the Button control in the Designer, VS will generate an event handler
for the Click event.
Listing 1 A WPF code-behind file
C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ControlsCS
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
}
}
}

No comments :

Post a Comment