Introduction to the Windows Presentation Foundation (WPF)

WPF is a graphical subsystem to the .NET framework.  It is essentially used to make UI programming easier by separating the UI from the business logic.  By doing this, it is easy to maintain and allows designers to easily change the UI without futzing with too much programming.  This, of course, makes it easier for the programmers because they don’t have to convert the design elements into application assets.  How does this all fit together?  I’ll go through a sample application in order to show how one might use the strengths of WPF to make application development a breeze.

For our example, I’ll pretend I’m making a browser application.  To keep it nice and simple, I’m only interested in the controls.  Being an expert graphic artist, I’ve crafted a stunning visual masterpiece:

Design

In order to create this amazing experience, all I had to do was drag-and-drop and edit the details using Visual Studio 2008’s design view:

For designers, Visual Studio 2008 will make it much easier.  However, it could still be a little daunting.  With WPF, the entire UI is laid out using XAML, which is an XML-based language that describes the layout, properties, and actions of the UI elements (I’ll go over this in more detail later).  Because of this, any program can be made to more easily lay out the elements of your window in the way the designers need (here‘s some examples) – all it has to do is output the result in XML-based XAML.

The best part for the programmer is that he doesn’t have to take the bitmaps created by the designer in photoshop, break them apart, and create buttons.  All he has to do is add the XAML and add the code behind the elements (aka business logic).  Oh, and say the design completely changes?  While the XAML changes, the business logic remains the same – no need to change things on the back end (yeah, that’s how it should be).  This makes maintaining the application marginally better – major UI revisions could leave all of the business logic exactly the same.  Though you should probably considering adding some features if all your doing is adding a new coat of paint.

Programming

“But Andrew,” says the imaginary, whiney, no-designing programmer that presumably exists in my subconscious.  “What does all of this mean to me!?”  Well, imaginary programmer, maybe this blog isn’t JUST FOR YOU.  Maybe you should just go read man pages for the rest of the day…or you can just read the rest of this post, since it is for you.  I’d say the best idea would be to stop existing in my imagination and quit telling me to start fires.

XAML

I’ll start with XAML, since it’s the basis behind WPF (and I’ve already introduced it to you).  Like I mentioned earlier, Extensible Application Markup Language (XAML, typically pronounced ‘zammel’) is based on XML.  This makes laying out an application as easy as setting up your first Geocities webpage.  Like XML, it has the main tags (like <Window> or <Button>) with properties that define the tag.  Here’s the XAML for the browser control window:

 
<Window x:Class="WPFIntroduction.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Browser Controls" Height="121.38" Width="775" Keyboard.KeyDown="Window_KeyDown">
    <Grid>
        <Button Height="48" HorizontalAlignment="Left" Margin="32.844,18.564,0,0" Name="BtnBack" VerticalAlignment="Top" Width="50" Click="BtnBack_Click">
            <Image Source="Images\back.png" />
        </Button>
        <Button Height="48" HorizontalAlignment="Left" Margin="102.816,18.564,0,0" Name="BtnForward" VerticalAlignment="Top" Width="50" Click="BtnForward_Click">
            <Image Source="Images\forward.png" />
        </Button>
        <Button Height="48" HorizontalAlignment="Left" Margin="172.788,18.564,0,0" Name="BtnHome" VerticalAlignment="Top" Width="50" Click="BtnHome_Click">
            <Image Source="Images\home.png" />
        </Button>
        <Button Height="48" HorizontalAlignment="Left" Margin="242.76,18.564,0,0" Name="BtnStop" VerticalAlignment="Top" Width="50" Click="BtnStop_Click">
            <Image Source="Images\stop.png" />
        </Button>
        <TextBox Height="38.164" Margin="309.876,23.24,79.254,0" Name="AddressBar" VerticalAlignment="Top" />
        <Button Height="48" HorizontalAlignment="Right" Margin="0,18.564,12.138,0" Name="BtnRefresh" VerticalAlignment="Top" Width="50" Click="BtnRefresh_Click">
            <Image Source="Images\refresh.png" />
        </Button>
    </Grid>
</Window>

Notice the XAML namespaces defined in the root element – these are required for XAML files. These are the namespaces used in defining the various XAML elements.

You might be wondering just how the XAML text gets converted into a user interface. The XAML is actually converted into code. You might notice above that all of the tags in the XAML are actually control classes. Window, Button, and Image are all classes, and WPF actually instantiates objects of these classes at runtime. So, for each Button tag, we have a Button object. The object names are as defined: BtnBack, BtnForward, etc.  You can actually reference these objects in your code – and no need to instantiate or set them up in the constructor.

Business Logic

Now, this isn’t entirely automatic.  You do have to include a call to a method, namely InitiataiteComponent(), to create the UI elements contained in the XAML.  Where do you call this method?  Well, each XAML window has a file that contains the code behind the XAML.  The Window created by the XAML is actually an inherited class.  In our case, the new class is Window1.  In this class’ constructor, the call to InitializeComponent() is called.  This class also houses the business logic, or the code behind the application.

This is also the best place to add event handlers for your application.  Since I’m not making a full browser, we’ll just stick with dialog boxes when buttons are clicked.  Here’s the whole class:

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 WPFIntroduction
{
    ///
    /// Interaction logic for Window1.xaml
    ///
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
 
        private void BtnBack_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Back button clicked");
        }
 
        private void BtnForward_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Forward button clicked");
        }
 
        private void BtnHome_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Home button clicked");
        }
 
        private void BtnStop_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Stop button clicked");
        }
 
        private void BtnRefresh_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Refresh button clicked");
        }
 
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter &amp;&amp; AddressBar.IsFocused)
                MessageBox.Show("New address entered");
        }
    }
}

Notice in the Window_KeyDown event, I reference the AddressBar object.

This is all pretty standard, so no need to really explain anything here – it’s simply some simple event handlers.  So, you have a basic WPF application to reference when creating your own WPF application.  While this, obviously, won’t get you to be able to create a brand new application in its entirety, it’ll give you a start to the mentality behind WPF.  I use this quite a bit, so don’t be surprised if I go into more in-depth examples in the future.  In the meantime, check out MSDN‘s resources on WPF…or feel free to ask questions. Lord knows I could have left plenty of details out.