WPF For The WinForms Developer

Introduction

 
I remember that a few years ago when .NET first hit the streets I thought that getting to grips with VB.NET from Classic VB was a steep learning curve.
Well let me put it this way: by comparison, learning WPF is like scaling a cliff face ... in a blizzard so it's hard to see where you're going, you've just dropped your crampons down a crevasse and have just discovered that the only directions for the route are in Serbo-Croat!
Am I exaggerating? Well, that's for you to decide when you set out on this climb yourself.

  I already have several books on the subject of WPF, and I'm sure I will own even more before I'm done. But one of the major problems I am finding with WPF is that it is just so complex that I need something simpler than a book several hundred pages thick to get me started. That's not to criticise the books; they are well written and comprehensive. But at this early stage what I need is a WPF 101, a "Hello WPF!" - even a "WPF For Dummies - as long as I can get kick-started. I can dig back into the intricate and clever detail once I've got a bedrock of basic understanding under my feet. I haven't found such a resource yet, and in particular very little for those of us who prefer VB to C# as our language of choice for the code behind. (And that's the "map of the route" problem I mentioned a moment ago.)

  So, in the absence of such a resource, I guess I'll have to create one myself.   
Welcome to "Hello WPF!" - the most basic of basic guides to using WPF.


Disclaimer:    Before we start, let's be clear on one thing. I am writing this as I learn WPF. So there are bound to be better ways of doing some of the things I describe, clearer and more accurate technical descriptions of what is happening and - let's face it - occasionally I'm probably plain going to get it wrong. No doubt I'll look back in three months time and think "Did I really say that?". But in the absence of anything else I hope it will be helpful to you if you too are just getting started.


The Tools

 I am currently using Visual Studio Codename Orcas Beta 1, so that's where the screenshots will come from. I'm sure the second Beta will be out before I'm very far through this guide, but hopefully most of the information will remain valid as the newer versions roll out. In any case I'll keep an eye on things and will come back and add comments if any parts of my narrative get overtaken by events.





 If you have held back from installing Orcas on your machine but still want to get started then you can install the Framework 3.0 Extensions for Visual Studio 2005. I can't promise that all my screenshots will match what you see (or even that all the facilities will be available in the earlier version). But it's an option that might suit your circumstances if you don't have a spare machine to run the Orcas Beta and don't want to take any chances of VS 2005 and Orcas not playing together nicely on the one system.

 Here are the links to download the Beta 1 and the WPF Extensions. Don't forget that you will need Framework 3.0 installed if you don't already have it and you are running Windows XP. (
Orcas Beta 1 can be found here. I'm using the installed (a.k.a. "Bits") version. This is the one which may break some elements of VS 2005 if you run them both on the same machine. I haven't taken the chance and have the two Editions on two separate systems.
  There is also a Virtual PC version which sidesteps this danger, but in my experience was difficult to install and can be a bit slow running.
Framework 3.0 Extensions for VS 2005 is here

 In addition to a series of introductory articles, I plan to include some videos to demonstrate techniques, especially of those parts where a (moving) picture is worth a thousand words. I have a copy of the excellent Camtasia Studio product and plan to use this for the job. The only thing holding me back is that if you thought my long winded writing style is boring then my quiet unexciting voice is almost sure to send you into a stupor of bad dreams about WPF gone wrong! When I get to that stage, I'll probably package up these notes together with the videos and make them available as one of the free courses in the VBCity Academy. That way, students can give me feedback and get help on any areas that aren't clear.


Getting Started

 Fire up Visual Studio and Create a new project. Select "Visual Basic" from the left hand pane and "WPF Application" from the right. Name it "HelloWPF1"





Note that you can change the Framework version that you are programming against in this new version of Visual Studio. The default of Framework 3.5 is fine. (In fact WPF is based on Framework 3.0 but there's no obvious benefit to be gained by selecting the lower version)

 When you create this project, you will see the default layout:



Default Display of WPF Project



 As you can see, the left side of the screen is split into two vertical panes; the upper one showing the Design view and the lower one showing the XAML Code view.


XAML

   XAML! Remember that this is strictly WPF 101 (Janet and John Do WPF), so I'm only going to give minimal explanations as we go through; just enough for you to actually begin to create something. Deeper meaningful explanations and discussions you can get from those books I mentioned, once you've got past the very basics.

  XAML is not WPF and WPF is not XAML. Let's get that straight. They work with each other, but they are different beasts. XAML is a declarative markup language, along the lines of HTML, and is a highly extended variety of XML. It's pronounced "zammel", but it works the same no matter how you pronounce it!
In WPF projects XAML is used to describe User Interface (UI) elements.

 WPF - Windows Presentation Foundation (quite possibly, as someone pointed out recently, the least sizzling name ever invented by the Marketing Department) - is the total graphical display system. It's the API (the framework -with a small f - if you like) for the new Windows graphics system.

 You can program in several intermixed languages within WPF. XAML is one of those languages. VB and C# are others.

 A key concept to grasp in WPF developing is that you can (and almost certainly will) program in both XAML and your .NET language of choice (from here onwards in the articles this is assumed to be VB). Theoretically you can program totally in one or the other and still create a WPF application; realistically the times you may want to do this are few.

 If you've programmed in ASP.NET you will be familiar with the concept of Code Behind. And if you've used VB 2005 you will know about Partial Classes. Partial Classes were introduced in VB 2005, mainly I believe as a tool to hide much of the code that was automatically generated by Visual Studio. It was introduced mainly to stop the uninitiated from tinkering from things which often should be left tinker-free.

 WPF also uses this Partial Classes approach. And, as with VB 2005, in many cases you won't need to tinker with the automatically generated code. In fact in the current version, the code which is automatically created by the tools for you doesn't appear in Solution Explorer at all (not even if you select the "Show All Files" option. This of course may change by the time the final version ships.

With Partial classes, what happens at compile time is that the two parts of the VB code (i.e the available ".vb" file and the not-so-available "g.vb" file are combined to make the whole. In WPF, there is an additional step in which the XAML is compiled and the whole shooting match then put together to create the whole finished product.

In most situations you will use XAML to create the graphical user interface and VB to code the events, (such as what happens when a button is clicked and so on.) You are not strictly forced down this route but it is the intended and generally recommended approach in most cases.


The Default Layout - Window and Grid

Getting back to that default opening layout, you will see that there is a Window which is named Window1. Be clear about this; it's not a Windows Form as in VS 2005, it's a Windows.Window. Contrary to that old saying that "If it looks like a duck and quacks like a duck then it's a duck", it may look like a WinForm but it's not a WinForm and there are differences.
(As it happens, at a lower level they do both stem from the same Win32 source, but for the purposes of our high level WinForms vs WPF Window overview they are different end results)

 And speaking of differences, you'll have noticed that it appears to have a Text property which (as in WinForms) defaults to the name of the Class.
Well, actually, it doesn't have a Text property. It has a Title property, and that property is set currently to "Window1". So if you struggled to change your Classic VB mindset from VB6's "Caption" to VB.NET's "Text", get yourself ready for yet another shift. The text displayed at the top of the Window is now the Title property. To be fair, this makes sense; it is the Title Bar, after all.

  Overlaid on that Window is a Grid. Now I agree it doesn't look much like a grid - isn't a grid supposed to be, well, grid-like? With lines to break it up into cells? Patience, my friend, we'll get to that in a minute. For now, click the Grid in the Design view and then take a look at the XAML code at the bottom of the display. You will see that the code editor has highlighted the XAML code for the control you just clicked on, i.e. the grid.

 There is no code between the tags and that's something we'll be addressing soon. There are several ways you can add markup code. You can type it straight in there to the XAML Editor pane if you know what you need. The syntax isn't always intuitive (and that's putting it mildly!), but in fact after only a very short time I think you'll develop a "feel" for the XAML code layout and it will become fairly easy to read. Especially if you use a lot of whitespace and don't try and cram too much on single lines of code. Luckily, in Orcas and the final version you have Intellisense on hand. (I don't think this is available in the VB 2005 Extensions version though).



Intellisense helps!



 In many cases you can use the Design Pane. With this grid, for example, you can click on its top or left edge and a marker - which looks something like a timeline marker or a narrow splitter - will appear. You can then drag this marker along and when it is in a position where you want a column or a row to be defined you simply release the mouse button. (This is one of those features where the Camtasia video recording will be much better to explain what is happening.) Here's a screenshot showing the creation of the first column divider:



Create a column visually



While you're looking at that screenshot, check out the numbers that are displayed along that top margin of the Grid. These indicate the width of each of those columns in units. I'm not going to get into a discussion of units at this early stage. What you need to know for now is that WPF is resolution independent, which means goodbye to those blocky, pixelated bitmaps of the past and hello to images which scale perfectly no matter what size the screen or zoom factor of the image.


Grid Sizing

The values showing on that grid currently are 173 and 119 units. And of course as you move that marker, so the values will change, which is the behaviour you would expect.

 Meanwhile, down in the XAML code pane things are happening. Two new lines of code have been inserted inside the code for the Grid. These are ColumnDefinitions, one per column. So, if you now look at the XAML code you would probably expect the widths to be 173 and 119 there too. But, in another quirk of WPF, the values are quite different.



Star or Proportional Sizing



 I probably shouldn't use the word "quirk" because that sounds like a criticism. And that would give the wrong impression. The sizing options in the grid control are wide ranging and sophisticated. You can set absolute sizes, relative sizes, automatic sizing to content, to name but a few. You can even link columns and rows in completely different grids so that as a specific column in one grid is resized, so the corresponding column in another, separate grid is also resized to match (and ignoring other controls that may be placed to physically divide the two grids). The choices are mighty impressive, but initially can be quite confusing.

 So at this very early stage in the WPF journey I'm going to suggest that you set the column widths and the row heights using the mouse as demonstrated. In a later Part of this article we will look at those sizing and spacing options in much more detail. For now though we will try and keep is simple and deal with them as we actually need them. Otherwise we'll soon lose the plot in the minutiae of detail and wealth of options.

 To complete the grid, we'll go back to the Design pane and manually add dividers so that we have 2 columns and 3 rows:



A grid with 2 columns and 3 rows



As before, the XAML code has now been constructed for you, again using the star (proportional) sizing as decreed by your choices in the Design pane.


First Viewing

 I thought it might be interesting for you to run the project so far and see what there is to be seen. So if you have been creating a project to mirror the story so far you can hit F5 now and run it. But before you do, don't build your hopes up. There isn't much to be seen!
Actually there's almost nothing to be seen, except for the plain white default background of the window. No sign of the grid though.

   No Grid Lines

 While this may seem strange at first, it is by design. The grid is essentially a design time layout tool. It isn't a presentation control in that it's not one of those kinds of GUI controls where you would expect to see its lines, margins or background colours, etc displayed on screen at run time. (It's maybe a bit misleading to call it "a design time tool" as this might give the impression that it has no purpose or worth at run time. This is far from the truth. The settings you apply at design time have major impact on what happens at run time; it's simply that it sits in the background very unobtrusively doing its stuff when the application is running.)

  Once you start to add other controls and place them in cells in the grid, its role will become more obvious. The thing to keep in mind is that those marker lines are only visible at design time in the Designer pane. Of course there are ways you can identify the individual cells at run time if you really need to. Plenty of them. And one of the easiest of these is to use the ShowGridLines property. (Bear in mind that the role of this property is to help you identify the grid's area while you are developing; it isn't really intended to be part of a finished distributed application.)

  Simply insert this property inside the code for the Grid:

ShowGridLines Property of a Grid

 Now when you run the project again you will see that the grid column and row dividers are identified for you:

Grid Lines Visible

  If you change the size of the window, notice that the grid automatically resizes to fill the available space. This happens because the default setting of the grid's Height and Width properties is "Auto". You can change this and hard code actual values for either if you need to.

 Note also that as you drag and resize the window, each column and row retains its proportional size relative to the other columns, cells and indeed the grid itself. This proportional resizing is a huge benefit available in WPF.

  So this seems like a logical point to end this Part of the article. We don't have much to see yet, but I hope that you will find the next section to be more graphically interesting, while at the same time we will continue to get a feel for how this new WPF technology works.





    Last updated 24th July 2007