Hello WPF World, part 3 – Forms and Windows

We continue with our basic “hello world” WPF application by adding a button to our main window and then building and running the application.  We also talk about the difference between forms in Windows Forms and windows in WPF, as well as how to add event handlers.

I want to insert a caveat at this point.  These first few “hello world” posts are basic—very, very basic.  Adding a button to a form and having it display a message box is what most of us do in the first five minutes that we spend playing with a new language or framework.  So don’t expect any cosmic secrets here.  I just want to take a little time to throw together a super simple application and then comment a little bit on what I’m seeing.

Form vs. Window

Let’s start by just building our basic wizard-generated application and then running it.  I’ll continue doing parallel stuff in a Windows Forms application, so we can compare the two.  Here’s what we get when we run the applications:

Form vs. Window

Form vs. Window

Nothing too earth-shattering here, although WPF has gotten rid of two old standbys that I’m sick of—the little multi-colored default application icon and the battleship grey form background.  Good riddance to both of them.

In both cases, we get a simple window with the standard window decoration elements.  Nothing appears to have changed here.  But if we look at the type that implements the window in either case, we see that everything is different under the covers.

Win Forms is using a System.Windows.Forms.Form (System.Windows.Forms.dll), while WPF’s main window is a Systems.Windows.Window (PresentationFramework.dll).

I’m curious, so let’s compare the two classes briefly.  (If you don’t already know about it, now is a good time to teach yourself Ctrl-Alt-J in Visual Studio for popping up the Object Browser).

The inheritance tree for a Win Forms Form is:

And the inheritance tree on the WPF side, for the Window, is:

(I included MSDN’s basic description of each class).  We won’t go any deeper than this for now, but the point is that, for WPF, things are very different under the hood.

One difference to note is that WPF does not support MDI (Multiple Document Interface), whereas Windows Forms does.  I could see a case for continuing to support MDI functionality for those who need it, but I can also see why it’s not worth carrying the old MDI framework forward.  It’s rare to see applications that support MDI in exactly the way that Win Forms supported it (windows entirely contained within parent window, etc).  When you do see a parent window containing child windows, the visual interface is likely different from the traditional sizable child windows—e.g. using a series of tabs.  There are so many different ways of doing this that it’s just easier to roll your own mechanism.  Or perhaps we could get some support in WPF in the future for a more updated and customizable implementation of MDI.

Another good way to see what goes on behind the scenes for the main form/window classes is to look at their lifecycle, as described by the events that the classes fire.  I always end up wanting to keep these “window lifetime” event lists for reference purposes, so they’re worth jotting down here.

Forms.Form events (Win Forms)

Loading/opening new form (application startup), events fired are:

Move
LocationChanged
StyleChanged
BindingContextChanged
Load
Layout
VisibleChanged
Activated
Shown
Paint

Closing a Win Forms Form, the events that fire are:

FormClosing
FormClosed
Deactivate

Windows.Window events (WPF)

Loading/opening new window (application startup), events fired are:

Initialized
IsVisibleChanged
SizeChanged
LayoutUpdated
SourceInitialized
Activated
PreviewGotKeyboardFocus
GotKeyboardFocus
LayoutUpdated
Loaded
ContentRendered

Closing a WPF Window, the events that fire are:

Closing
IsVisibleChanged
Deactivated
Closed

Adding a Button

Now let’s add our first control to the WPF window in our application.  We’ll add a button to the window by just dragging it onto the design surface in the XAML designer.

The designer ends up looking something like this:

And the XAML snippet in the bottom window is also updated as soon as we add the button:

Note that everything we do in the designer  is immediately reflected in the XAML.  This is because there is an exact match between what the designer renders and what is stored in the XAML.  You can think of the designer (or design surface) as nothing more than a combination XAML viewer and XAML editor.

We can also demonstrate here that working in the opposite direction works as expected—if you edit the XAML, the designer updates immediately to reflect your changes.  Note that we don’t even have to save the file—the content in the designer changes immediately, as we type!  You can also edit property values in the Properties window that is docked to the right of the designer (under the Solution Explorer).

Let’s take a look now at what happens in our generated code, once we have a couple of controls on the design surface.  I’ll add a CheckBox to the window and then open up Window1.g.cs.  Note that this source file is not updated until we build (since it’s generated from the XAML whenever we build).  If we rebuild the project now and take a look, we’ll see that both controls have been declared at the top of our partial class and that the Connect method includes them in its switch statement:

This code is creating/initializing the controls at runtime, based on the content in the BAML memory stream that was included in our assembly.

Event Handlers

Now it’s time to wire up our first event handler so that we can do something when the button is clicked.

At first glance, something important is missing from Visual Studio.  When we have the WPF Designer open for our main window and have selected our button, the Properties window doesn’t seem to list any events.  Entirely missing is the little event icon that lets us get a list of all events for the currently selected control.

The question then becomes—what designer support do we have for adding event handlers in a WPF application?  The answer is to edit the XAML directly.  If we position the cursor at the end of the attribute list for the Button element in our XAML editor and press space, we see a nice intellisense popup listing all available attributes (properties and events).  Note the presence of the Click event in the image below:

If we select the Click event, or start typing “Click”, the editor adds a new attribute for the Click event and the intellisense window changes to indicate <New Event Handler>.  At this point, we can dbl-click on <New Event Handler>  to generate our event handler, or—better yet—just press the TAB key to generate the handler.

Once we’ve created the default event handler, our XAML looks like this (note the default handler name):

Now we can open our partial class implementation of Window1 in Window1.xaml.cs and we see our empty handler that has been generated for us:

Hello World

We’re finally ready to add some “hello world” code to our handler, which will execute when the Push Me button is clicked:

And—highly satisfying—we can run our program and get one of two message boxes to display, depending on whether the “verbose” checkbox is checked:

Next time, I’ll start looking in more depth at the various controls available in a WPF application, starting with the Button.

Advertisements

Hello WPF World, part 2 – Why XAML?

Let’s continue poking around with a first WPF “hello world” application.  We’ll continue comparing our bare bones wizard-generated WPF project with an equivalent Win Forms application.  And we’ll look at how XAML fits into our application architecture.

Last time, we compared the Win Forms Program class with its parallel in WPF–an App class, which inherits from System.Windows.Application.  The application framework in Win Forms was pretty lightweight–we just had a simple class that instantiated a form and called the Application.Run method.  WPF was just a bit more complicated.  If we count the generated code, we have an App class split across a couple of files, as well as a .xaml file that defines applicaton-level properties (like the startup window).

Now let’s compare the main form in our Win Forms application with the main window generated for us in WPF.  (The fact that WPF calls it a window, rather than a form, hints at the idea that GUI windows aren’t meant to be used just for entering data in business applications).

In Windows Forms, we have two files for each form–the form containing designer-generated code (e.g. Form1.Designer.cs) and the main code file where a user adds their own code (e.g. Form1.cs).  These two source files completely define the form and are all that’s required to build and run your application.  In Windows Forms, the designer renders a form in the IDE simply by reading the Form1.Designer.cs file and reconstructing the layout of the form directly from the code.  (The IDE does create a Form1.resx resource file, but by default your form is not localizable and the resource file contains nothing).

When you think about it, this approach is a bit kludgy.  The designer is inferring the form’s layout and control properties by parsing the code and reconstructing the form.  Form1.Designer.cs is meant to contain only designer-generated code, so with partial classes, we can keep designer-generated code in a single file and it only contains designer code.  But it’s clumsy to use procedural code to define the static layout of a form.

Here’s a picture of how things work in Win Forms:

In this model, the Form1.Designer.cs file contains all the procedural code that is required to render the GUI at runtime–instantiation of controls and setting their properties.  We could dispense with the designer in Visual Studio—it’s just a convenient tool for generating the code.  (I’m ashamed to admit that I’ve worked on projects that broke the designer and everyone worked from that point on only in the code–ugh)!

Now let’s look at WPF.  Here’s a picture of what’s going on:

Note the main difference here is–our designer works with XAML, rather than working with the code.  This is the big benefit of using XAML–that the tools can work from a declarative specification of the GUI, rather than having to parse generated code.  This also means that it’s easier to allow other tools to work with the same file–e.g. Expression Blend, or XamlPad.

Then at build time, instead of just compiling our source code, the build system first generates source code from the XAML file and then compiles the source code.

But this isn’t quite the whole story.  It’s not the case in WPF that the Window1.g.cs file contains everything required to render the GUI at runtime.  If we look at the Window1.g.cs file, we don’t find the familiar lines where we are setting control properties.  Instead, we see a call to Application.LoadComponent, where we pass in a path to the .xaml file.  We also find a very interesting method called Windows.Markup.IComponentConnector.Connect(), which appears to be getting objects passed into it and then wiring them up to private member variables declared for each control.  If we add a single button to our main window, the code looks something like:

But then the obvious question is–what happened to all those control properties?  Where do the property values come from at runtime?

Enter BAML–a binary version of the original XAML that is included with our assembly.  Let’s modify the above picture to more accurately reflect what is going on:

Note the addition–when we build our project, the contents of the XAML file–i.e. a complete definition of the entire GUI–is compiled into a BAML file and stored in our assembly.  Then, at runtime, our code in Window1.g.cs simply loads up the various GUI elements (the logical tree) from the embedded BAML file.  This is done by the Connect method that we saw earlier, in conjunction with a call to Application.LoadComponent:

MSDN documentation tells us, for LoadComponent, that it “loads a XAML file that is located at the specified uniform resource identifier (URI) and converts it to an instance of the object that is specified by the root element of the XAML file”.  When we look at the root element of the XAML file for our application, we discover that it is an object of type Window, with the specific class being HelloWPFWorld.Window1.  Voila!  So we now see that the code in Window1.g.cs which was generated at build time just contains an InitializeComponent method whose purpose it is to reconstitute a Window and all its constitutent controls from the GUI definition in the XAML file.  (Which went along for the ride with the assembly as compiled BAML).

So what is BAML and where is it?  BAML (Binary Application Markup Language) is nothing more than a compiled version of the corresponding XAML.  It’s not procedural code of any sort–it’s just a more compact version of XAML.  The purpose is just to improve runtime performance–the XAML is parsed/compiled at build time into BAML, so that it does not have to be parsed at runtime when loading up the logical tree.

Where does this chunk of BAML live?  If you take a look at our final .exe file in ILDASM, you’ll see it in the manifest as HelloWPFWorld.g.resources.  Going a tiny bit deeper, the Reflector tool shows us that HelloWPFWorld.g.resources contains something called window1.baml, which is of type System.IO.MemoryStream.  (I found something that indicated there was also a BAML decompiler available from the author of Reflector, which would allow you to extract the .baml from an assembly and decompile back to .xaml–but I couldn’t find the tool when I went looking for it).

So there you have it.  We haven’t quite yet finished our “hello world” application, but we’re close.  We’ve now looked in more depth at the structure of the application and learned a bit about where XAML fits into the picture.  Next time, we’ll add a few controls to the form and talk about how things are rendered.

Hello WPF World, part 1

All right, it’s time to create our first “hello world” application in WPF.  Let’s just use the Visual Studio wizard to create an application and then poke around to see what we got.  (Yes, I know I’m a bit late to the WPF game, but let’s just get started).

We’ll start by doing a New Project in Visual Studio 2008.  Under Visual C# (I’m a C# guy), select Windows to see projects related to thick clients.  If you change the targeted .NET Framework to version 3.0 or 3.5, you’ll see the following WPF project types:

  • WPF Application
  • WPF Browser Application
  • WPF Custom Control Library
  • WPF User Control Library

This seems pretty straightforward.  We’re building an application, rather than a control library.  So we want to create a WPF Application. I’ll explore creating WPF controls later.

Now it’s time to see what the project wizard created for us in our project.  As we walk through the solution, let’s compare the pieces with an equivalent “hello world” application in Win Forms, just to see how WPF differs.

AssemblyInfo.cs

For starters, both projects have an AssemblyInfo.cs file that describes metadata for the assembly.  Cracking them open,  they’re pretty similar, as expected.  But there are a couple of differences.

The WPF project includes a couple additional namespaces—System.Resources and System.WindowsSystem.Resources is added for the NeutralResourcesLanguage attribute.

System.Windows is, surprisingly, a new namespace for WPF, containing a lot the high-level WPF classes and types.  In this case, we’re using the ThemeInfo attribute and the ResourceDictionaryLocation enumeration.

The first new chunk of stuff in the WPF file is a commented out instance of the NeutralResourcesLanguage attribute and a comment about adding an <UICulture> tag to your project, if you want your application localizable.  Adding the <UICulture> tag  to your project file will tell the project that it should be localizable, and causes creation of the external satellite DLL.  We’re also instructed to uncomment the NeutralResourcesLanguage attribute, and setting the culture to match the <UICulture> tag—which indicates what our “neutral” language is, i.e. the native language of the assembly itself.  This reportedly speeds performance during the resource fallback process—runtime won’t  bother looking for an external resource DLL if the thread’s CurrentUICulture matches the neutral culture of your assembly.  A little unclear why the attribute is required—possibly just to make sure you set the neutral culture to match the <UICulture> tag.

Next, the WPF AssemblyInfo.cs file contains an instance of the ThemeInfo attribute.  This attribute has to do with defining theme-specific resources for your controls—i.e. you define a set of resources that applies a style to your controls, depending on which Windows theme is active.  Looks like a topic for a future post.

Resources.resx & Resources.Designer.cs

The default resources file created by the project wizard is the same for a WPF application as for a Win Forms application.  We get an empty resource file and an internal class that will be used to contain strong-typed string resources.  (The strongly typed resources were new in VS2005 and offer the huge benefit of being told at compile time that you misspelled a resource name, rather than just having the resource not be found at run time).

Settings.settings & Settings.Designer.cs

The default settings file in WPF is the same as the Win Forms file, with one subtle difference.  The WPF version uses an XML namespace of “uri:settings”, rather than the Win Forms explicit namespace, which is “http://schemas.microsoft.com/VisualStudio/2004/01/settings”.  I’m not enough of an XML or a URI/URN guru to understand the difference here, other than observing that the WPF version is more generic.  It’s also interesting to see that using “uri” for the URI scheme (the part before the colon) is not an official IANA-registered usage.  (See http://en.wikipedia.org/wiki/URI_scheme).

Assembly References

The WPF project references three new assemblies for WPF : PresentationCore, PresentationFramework, and WindowsBase.  These just contain new WPF types, sprinkled across many different namespaces.  (By the way, if you’re curious about the total # types in the Framework, take a look at this post by Brad Abrams: http://blogs.msdn.com/brada/archive/2008/03/17/number-of-types-in-the-net-framework.aspx).

Out of curiosity, I ran NDepend on these WPF assemblies and came up with the following metrics.  PresentationCore – 2,711 types,  PresentationFramework – 2,306, and WindowsBase – 785.  And these are just a subset of the assemblies introduced for WPF in .NET 3.0!

The WPF project does not reference the System.Deployment, System.Drawing or System.Windows.Forms assemblies.  System.Drawing and System.Windows.Forms include GDI+ and Windows Forms functionality, respectively, so it’s obvious why we no longer need them in WPF.  System.Deployment is related to deploying with ClickOnce and it’s not clear why the Win Forms project included it by default.

App.xaml vs. Program.cs

Now we come to the core differences between a Win Forms and a WPF application.  In terms of what you see in the WPF project, the App class couldn’t be simpler—an empty partial class deriving from System.Windows.Application and a mostly empty XAML file:

App.xaml.cs

App.xaml.cs

App.xaml

App.xaml

Wait a minute!  Where’s my Main() function?  In the wizard-generated Win Forms project, we got a Program.cs file with a Main(),  which called System.Windows.Forms.Application.Run, passing it an instance of our main form.  But how does the WPF application start itself up?

The hint is that our App class is declared as a partial class.  If we right-click on the App class and select Go To Definition, we can hunt down the file App.g.i.cs (in the \Debug or \Release folder, if we’ve built our application).  You can also click Show All Files in the Solution Explorer and expand the obj\Debug folder, finding App.g.cs.  (These files appear to be identical—perhaps the i.cs file is generated by Intellisense)?

The magic that creates these generated files at build time comes from the <Generator>MSBuild:Compile</Generator> line in our .csproj file, for the App.xaml file (under ApplicationDefinition tag).  When App.xaml is built, MSBuild generates the actual code that represents what was declared in App.xaml, storing the code in App.g.cs.  The actual code generation magic happens in the Microsoft.Build.Tasks.Windows namespace, which lives in the PresentationBuildTasks assembly.  Sounds like another topic for a future blog.  (I started to get lost in Ildasm).

Now let’s take a look at the App.g.cs file.  It shows that we’re deriving from System.Windows.Application, which is the main WPF application class.  We also see that the InitializeComponent method is pulling stuff in from the XAML file.  In our case, all we have in App.xaml is a value for the StartupUri attribute, which pointed to the XAML file for our main window.  In our code, this maps to setting the StartupUri property of the Application class.  This is basically just—the UI that should be shown when our application starts.

App.g.cs

App.g.cs

The Main function is very similar to what we find in Program.cs for our Win Forms application—we just create an instance of our App class, call InitializeComponent to set stuff up, and call the Application.Run method.  It should be no surprise that the documentation for Run tells us that it creates a System.Windows.Threading.Dispatcher object, which creates a message pump to process windows messages.

Note that we could also call Run and pass it a Window object to indicate the first window to open when the application starts.  Instead, the generated code specifies the first window by setting the StartupUri property.

Next time: Looking at the Window1.xaml, Window1.xaml.cs and Window1.g.cs files, which define the application’s main window.

It’s a WPF World, part 2

Let me continue my ramble about Microsoft technologies leading up to WPF.  Last time, I ended by talking about the .NET technologies and why I think they are so important.  .NET has become the de facto standard for developing applications for the Windows platform (thick clients).  And although ASP.NET likely doesn’t have nearly as big a chunk of market share as Windows Forms, it feels like the WISA stack (Windows, IIS, SQL Server, ASP.NET) is gradually overtaking the LAMP stack (Linux, Apache, MySQL, PHP).  And with the rise of RIAs (Rich Internet Applications), ASP.NET Ajax will likely encourage the continued adoption of the ASP.NET technologies.

Going back to my list of the most important benefits of the .NET world from last time, I realized that I’d like to add a final bullet item.  (In the list–what’s so special about .NET):

  • Programmer Productivity — with things like intellisense and code snippets in Visual Studio, you can be incredibly productive, whether working in Win Forms or ASP.NET

I make the claim about productivity without having had experience with other development environments (at least since doing OWL development with Borland tools).  But the rise in productivity is true even just of Microsoft tools.  They just continue to get better and better.  And though “real programmers” might pooh-pooh all this intellisense nonsense in favor of hand coding in Textpad, I have to believe that even these guys would be more productive if they truly leveraged the tools.

When .NET first came out, I remember reading the marketing materials and being a little misled about where ASP.NET fit into things.  It seemed like Microsoft was touting convergence of Windows vs. web development, by talking up the similarities of the dev experience, working in Windows Forms vs. Web Forms.  Developing with ASP.NET was ostensibly very similar to developing Win Forms applications–you started with an empty design surface, dragged visual controls onto it, and double-clicked to bring up an editor where you wrote your code-behind.  (Nevermind that this model encouraged low quality architectures as people wrote monolithic chunks of event handler code–perpetuating bad habits that we learned with VB6).

But the web model was still very, very different from the thick client model.  On Windows, we were still working with an event-driven model, using the same old Windows message loop that we’d always used.  But users interact with a web-based interface in a completely different way.  We used server-side controls in ASP.NET to hide some of the complexity, but we were still just delivering a big glob of HTML to the client and then waiting for a new HTTP request.

The ASP.NET development environment also felt a bit kludgy.  I remember being a bit dismayed when I wrote my first ASP.NET application.  In the classic Win Forms development environment, there were two separate views of your application, where a developer lived–the design surface and the code behind.  The ASP.NET environment has three–the design surface, the code behind, and the HTML content.  So now instead of a developer jumping back and forth between two views, you end up jumping around in all three.

Spoiler–this web application architecture gets a lot cleaner with Silverlight 2.0.  There seems to be actual convergence between thick vs. thin clients as we use WPF for thick clients, Silverlight 2.0 for thin.  But more on that later.

So along comes WPF (Windows Presentation Foundation) and XAML (Extensible Application Markup Language).

I remember when I first read about XAML and WPF (Avalon at the time).  My first reaction was to be mildly frustrated.  At first glance, XAML seemed to be an arbitrary switch to a new syntax for defining GUIs.  And it seemed cryptic and unnecessary.  In the effort to be able to define a user interface declaratively rather than procedurally, it looked like we were ending up with something far messier and garbled than it needed to be.  It felt much easier to understand an application by reading the procedural code than by trying to make sense of a cryptic pile of angle brackets.

But I’ve come to realize that the switch to defining GUIs declaratively makes a lot of sense.  With XAML, thick clients move a bit closer to web applications, architecturally–the GUI is built from a static declaration of the UI (the XAML), a rendering engine, and some code behind.  And the layout of a user interface (rather than the behavior) is implicitly static, so it makes sense to describe it declaratively.  [As opposed to Windows Installer technology, which converts the dynamics of the installation process to something declarative and ends up being far messier].

Why does it make sense to separate the markup from the code like this?

  • Architecturally cleaner, separating the what (XAML declaraction of GUI) from the how (code-behind).  (Separating the Model from the View)
  • Enables broad tool support–tools can now just read from and write to XAML, since the GUI is now defined separately from the application itself.  (Enabling separate tools for designers/devs, e.g. Expression Blend and Visual Studio).
  • Cleaner for web apps — because we can now serialize a description of the GUI and send it across the wire.  This just extends the ASP.NET paradigm, using a similar architecture, but describing a much richer set of elements.

Another of my earlier reactions to XAML was that it was just a different flavor of external resource (.resx) files.  It looked similar–using angle brackets to describe GUI elements.  But XAML goes far beyond .resx files.  Resource files are used to externalize properties of UI controls that are potentially localizable.  E.g. Control sizes, locations and textual elements.  But the structure is flat because a resource file is nothing more than a big collection of keyword/value pairs.  Nothing can be gleaned about the structure of the UI itself by looking at the .resx file.  XAML, on the other hand, fully describes the UI, hierarchically.  It is far more than a set of properties, but it is logically complete, in that it contains everything required to render the GUI.

XAML is a big part of what makes WPF so powerful.  But there are a number of other key features that differentiate WPF from Windows Forms.

  • Totally new rendering engine for the GUI, based on Direct3D.  This enables better performance in rendering of the GUI, because everything in your GUI is described as 3D objects.  So even apparent 2D user interfaces can take advantage of hardware acceleration on the graphics card.  [The new NVidia GT200 GPU has 1.4 billion transistors, compared with original Core 2 Duo chips, which were in the neighborhood of 300 million].
  • Vector graphics.  The GUI is now entirely defined in vector graphics, as opposed to bitmapped/raster.  This is huge, because it means that you can define the GUI geometry indepedent of the target machine’s screen resolution.  This should mean–no more hair-pulling over trying to test/optimize at various screen resolutions and DPI settings.  (Gack)!
  • Bringing other APIs into the .NET fold.  E.g. 3D, video, and audio are now accessible directly from the .NET Framework, instead of having to use APIs like DirectX.
  • Focus on 3D graphics.  All of the above technologies just make it easier to develop stunning 3D graphical user experiences.  Powerful/cheap graphics hardware has led to 3D paradigms like Apple’s “cover flow” showing up more and more often in the average user interface.  (Battleship Grey, you will not be missed))

So where does WPF fit into the rest of the .NET world?  Is WPF a complete replacement for Windows Forms?

Adopting WPF will not be nearly as big a learning curve as adopting .NET was, originally.  WPF is a full-fledged citizen of the .NET world, existing as a series of .NET namespaces.  So .NET continues to be the premiere Microsoft development technology.

WPF is definitely a replacement for Windows Forms.  It is the new presentation layer, meant to be used for creation of new Windows-based applications (thick clients).  Microsoft is probably hesitant to brand WPF purely as a Windows Forms replacement, not wanting to dismay development shops that have invested a lot in learning .NET and Windows Forms.  But it’s clearly the choice for new Windows-based UI development, especially as the number of WPF controls provided by the tools, and shipped by 3rd party vendors, increases.

WPF is also highly relevant to web development (thin clients).  Silverlight 2 allows a web server to deliver browser-based RIAs containing a subset of the widgets found in WPF.  (Silverlight 2 used to be called Windows Presentation Foundation/Everywhere).  With WPF and Silverlight, Windows and web development are definitely converging.

So we clearly now live in a WPF world.  WPF will rapidly become more widely adopted, as it is used for more and more line-of-business applications, as well as serving as the underlying engine for the new Silverlight 2 RIAs that are starting to appear.  And the best news is that we also still live in a .NET world.  We get all of the .NET goodness that we’ve learned to love, with WPF being the shiniest new tool in our .NET toolbox.