WPF, the Windows Presentation Foundation, is a .NET API for building Windows applications. Much has been written about how WPF makes it easier than ever before to create visually impressive applications, but it has other talents which, although less eye catching, make WPF a powerful technology for building front ends. In particular, the .NET framework's strong support for connected systems combined with WPF's approach to data binding to make it a compelling choice for presenting information from back-end services written in any technology, such as Java, Ruby, or .NET.
In this article we will compare WPF to alternatives such as Ajax/DHTML, Swing, and Flash; we will then look at some scenarios where you might usefully build a WPF front end as a rich client, using back-end services based on Java for example.
A Short Guide to WPF
WPF is a platform for building rich client applications. It part of the .NET 3.0 Framework, so it is built into Windows Vista, and can also be installed on Windows XP service pack 2, and Windows 2003. WPF user interfaces are constructed as .NET object models. However, WPF offers XAML - the eXtensible Application Markup Language - which is a markup language that allows the user interface's appearance to be designed separately from the code that defines its behavior. Either approach is equivalent, XAML being just an alternate syntax. However, the XAML syntax is designed to be easy for tools to create and consume, the intention being that tools will be created to enable designers to get directly involved in creating user interfaces, without needing coding skills.
(For more detailed information about WPF, see http://wpf.netfx3.com/ )
WPF is not the first rich client API to be available in .NET. However its predecessor, Windows Forms, is essentially a .NET layer on top of Win32's windowing system. And while Windows Forms added a lot of functionality on top of Win32, it was still constrained by certain limitations in the underlying UI platform. WPF does not build on Win32's windowing system. Instead, it builds on DirectX, which enables it to exploit the full power of the local machine's graphics card. However, WPF is not just about impressive-looking applications.
The single biggest benefit WPF has to offer is that it integrates many rich client features into a single platform. Most of these individual features have been available in isolation in other UI technologies for some time. For example, WPF offers animated vector graphics and video, which have long been Flash's fortes. WPF offers ordinary Windows controls such as buttons, list boxes, and tree views, which have been available in Win32 and Windows Forms for years. It offers flowed text layout, something HTML has done from the start. (Although WPF's text rendering is significantly more advanced than HTML and CSS are today.) WPF's markup + code-behind style of application construction also draws directly from HTML-oriented technologies such as JSP and ASP.NET. It has some basic 3D support, but OpenGL and DirectX have been able to do more advanced 3D rendering for many years.
WPF's predecessors are all good at what they do, but it's very difficult to use features from multiple technologies in a single application. It's very hard to use Flash's animation facilities in conjunction with Windows buttons and combo boxes. (Flash applications tend to define their own controls, but these typically fail to integrate visually with the user's chosen OS visual theme, they often fall short on accessibility, and their behavior is usually inconsistent with real controls.) Using data binding in a rich client application in conjunction with the text layout services offered by HTML is not well supported. In general, when you try to mix technologies, your application ends up split into multiple different worlds. Getting anything to span the divide is at best inconvenient, and often impossible.
By contrast, WPF makes this easy. Unfortunately, many of the publicly available WPF examples demonstrate this integration somewhat gratuitously. Wrapping full-motion video onto a rotating cube that forms part of the caption of an otherwise normal-looking Windows button embedded in the middle of a flow layout document might be a convincing demonstration that the various different UI features can all be brought together, but it also raises the question: who in their right mind would design a real application that way?
In reality you would be unlikely to integrate every possible UI feature into an application. To do so would be reminiscent of the early days of the web, where many sites would try to use every possible HTML feature without applying much thought. The results were horrendous. It took time to learn how best to use the technology to build good web applications. Likewise, the freedom to use WPF's visual features in any combination is powerful and liberating, but a little taste and restraint will be necessary to build useful applications. Moreover, WPF has a lot to offer even to fairly visually unadventurous applications.
Why Build a WPF Front End?
To discuss meaningfully why you might want to build a WPF front end, we need to compare it with some alternatives. Some obvious candidate technologies would be the web, Swing, Flash, Windows Forms, or even Win32.
Compared with a web front end, WPF enables higher quality interactivity. The standard of interactive web apps has improved lately, but while AJAX offers massively better interactive behaviour than classic plain HTML, that's really not saying much. We have become so accustomed to the web that we barely notice its many egregious interaction problems, and we are blown away by web sites that manage merely not to suck. Even best-of-breed AJAX applications deliver a user experience that would qualify as pretty ordinary by rich client standards. Moreover, although AJAX tools are coming on in leaps and bounds, it still requires a great deal more effort to deliver a satisfactory interactive experience with AJAX than it does to produce something at least as good with a rich client technology. Also, WPF applications can work even when the client machine is disconnected from a network. Moves are afoot to solve this problem for web applications, but today, rich client applications offer the only convincing solution for users with intermittent connectivity.
Compared with Swing, WPF offers two notable benefits. The first is WPF's data binding system, especially the XML binding and the data template features, which are discussed later in this article. The second advantage is a double edged sword that is also a reason you might not want to use WPF: WPF is designed to run only on Windows. This means it is able to take full advantage of the local PC's capabilities, and especially the power of the graphics hardware. This enables features such as high performance rendering of advanced data visualization, or more cosmetic touches like animation and video.
While Flash can offer some of the same cosmetic flourishes as WPF, such as animations and video playback, it's weaker if you want to build applications that look and behave like ordinary Windows programs. One of WPF's great strengths is that it offers both advanced visual features and a standard set of Windows controls that behave in the way users expect, allowing you to use both, mixed freely within a single application.
Compared with other Windows-specific rich client technologies such as Windows Forms, or classic Win32 development, WPF offers better data binding features, and makes it much easier to produce rich data visualizations. While WPF offers many benefits, there are also some reasons you might choose not to use it.
Why Not Build a WPF Front End?
The most likely blocker for WPF will be non-availability of .NET 3.0 on the client. A WPF application absolutely requires the .NET 3.0 Framework to be installed on the end user's machine. If you need to support users running operating systems other than Windows, or they are using a version of Windows older than Windows XP service pack 2, this rules out WPF. And even if the client machines are running a suitable version of Windows, you may not be able to get .NET 3.0 installed.
(Even if this rules out WPF, it might not rule out WPF/E. This is UI platform offering a trimmed down subset of WPF's features. The ‘E' stands for Everywhere, since it will run on non-Microsoft platforms including the Firefox web browser, and Mac OS X. However, this hasn't shipped yet, which limits its utility today. In fact the very first public preview had only just shipped at time of writing. So it's early days for WPF/E, and it's not something you can build on right now.)
Another point to bear in mind is the memory footprint of a typical WPF application. Looking at the WPF applications currently running on my machine, their working set sizes are all competing with the Microsoft Office suite applications in vying for the title of ‘biggest memory hog'. (And these particular WPF applications all have significantly less functionality than any of the Office applications.) If you need to support client machines with small memory configurations, WPF may not be the best choice.
You may also want to consider whether you want to adopt Yet Another Technology. If you are already using .NET, WPF is attractive because it's just another part of the .NET world, making it relatively easy to learn and adopt. But if you are not already using .NET in your systems, you would need to consider whether the potential benefits outweigh the costs of adding to the set of technologies your developers need to know.
But assuming that none of these blocking factors apply, and the benefits look worthwhile, the next step is to consider what sort of WPF application you might build.
Application Types and Deployment Options
WPF applications come in several forms. They may offer a UI with web-like navigation, or they might opt for a more traditional forms-oriented style. They might run as standalone applications, or they could be hosted entirely within a browser frame. And there are various options for how the application might be deployed.
The traditional style of rich client application runs in its own windows instead of a web browser, and can be launched from the Start menu's Programs list. You can use this style without losing the central update model of a typical web application: WPF is able to use the .NET framework's ‘ClickOnce' deployment technology, enabling updates to be deployed to a web server, and downloaded by client machines automatically.
If you have an established web-based Java application, a standalone WPF application probably looks like a bit of a misfit. In this case, you could instead start to exploit WPF without disrupting the overall application structure by building one or more browser-hosted navigation style WPF applications. This kind of application is called an ‘XBAP' - a XAML Browser Application. (As mentioned earlier, XAML is the markup language often used to construct a WPF user interface.) This is a very similar model to Java Applets: an XBAP can be embedded into a web page, or it can stand in for a whole web page, and in either case it is hosted in a secure sandbox. You could augment or replace parts of your web application with XBAPs while leaving the overall information architecture in place. This avoids the need for an all or nothing approach to WPF, adopting it only in the places where it offers the most benefit. You may also be able to provide a fallback UI for clients without .NET 3.0, by serving ordinary web pages instead of XBAPs to such clients.
Yet another option is a pure markup approach. Instead of building XBAPs (which are always compiled applications) you could simply generate XAML. If a web server serves up XAML pages, then as long as the client supports WPF, it will parse and render the content. This may provide a particularly easy way to incorporate WPF content: if your web server content management system supports the ability to generate web pages using XSLT, you may be able to adapt this to generate XAML as well as HTML from the underlying source material.
If you are building a new application from scratch, this ability to adopt WPF piecemeal is less useful. In that case, you would probably go for a standalone client application. This then raises the question of how the client application will communicate with the Java service.
Connecting Client to Server
WPF is part of the .NET 3.0 Framework, which also includes WCF. (The Windows Communication Foundation is a technology for using and creating distributed services, and it supports a wide set of web service standards.) This suggests an obvious strategy for connecting a WPF client to a Java server: XML web services using WCF on the client side. However, this is not the only option. (This is just as well, because in some cases, you may be unable to use WCF. WCF does not currently support partial trust scenarios, meaning you cannot use it within an XBAP, for example.)
You can also use the .NET 2.0 style web service client features. WPF's data binding system is just as happy working with this system as with WCF. Indeed, it doesn't really care where the data came from. It's happy to use any old set of objects as a data source.
As well as being able to bind to objects, WPF also has excellent support for data binding directly to XML data. This makes a POX (Plain Old XML) approach eminently workable. The next section shows a simple example.
XML Data Binding
WPF is able to bind directly to XML as a data source. It does not require it to be wrapped in any way. To illustrate this, we'll bind to a very simple but very popular form of XML data: RSS. There are of course numerous different sources of RSS in the world, generated by any number of different technologies. In the following example, we're going to use an RSS feed from Sun's developer site. (It seems safe to assume that Java is likely to be involved somewhere in this particular server.) Here's a XAML fragment for a WPF user interface that presents some information from an RSS feed:
<Border BorderBrush="Black" BorderThickness="1" Padding="2">
<Border.Resources>
<XmlDataProvider x:Key="source" XPath="/rss/channel"
Source="http://developers.sun.com/rss/java.xml" />
</Border.Resources>
<StackPanel DataContext="{StaticResource source}">
<TextBlock Text="{Binding XPath=title}" FontSize="18"
FontWeight="Bold" Margin="0,5" />
<TextBlock Text="{Binding XPath=description}"
TextWrapping="Wrap" />
</StackPanel>
</Border>
The URL for the XML source is hard-coded here with an XmlDataProvider element to keep the example simple - in a real application there are many different ways you could get the XML into the application.
The most interesting part of this example is the pair of TextBlock elements nested inside the StackPanel. (A StackPanel is a layout component that arranges its child items in a vertical stack.) Each of the TextBlock elements is bound to part of the source XML document - the connection is described in each case with the ‘{Binding ...}' syntax. The XPath expressions in these elements are relative to the XPath expression in the XmlDataProvider element near the top of the example. So the first text block is essentially evaluating the expression /rss/channel/title, and presenting the result as text. Here's how the whole example looks.
We didn't have to do anything to the XML data in this example - we just fetched it in its raw form from the web. WPF's data binding services let us point XPath expressions directly at the data we wish to display. This approach will work for any service (Java or otherwise) that exposes data in XML form.
This example only shows singular pieces of information from the feed. We can produce something more interesting with only a little more effort by taking advantage of another WPF data binding feature: data templates.
Data Templates
A data template is a reusable description of how to present a piece of data. You can apply a data template to multiple items, e.g. every item in a list, in order to present information consistently. The following example can be added inside the StackPanel of the previous example. This creates a ListBox control, whose items in this case are the set of ‘item' elements in the RSS feed:
<ListBox ItemsSource="{Binding XPath=item}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="2,8">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Title:" Margin="0,0,0,6" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="Description:" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="Link:" />
<TextBlock Grid.Row="0" Grid.Column="1" FontWeight="Bold" FontSize="14"
Text="{Binding XPath=title}" TextWrapping="Wrap" />
<TextBlock Grid.Row="1" Grid.Column="1"
Text="{Binding XPath=description}" TextWrapping="Wrap" />
<TextBlock Grid.Row="2" Grid.Column="1" Foreground="Blue"
Text="{Binding XPath=link}" TextDecorations="Underline" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Each item in the list is presented by a DataTemplate, which in this example has been specified inline inside the ListBox. This template shows how to arrange and format each item, and which pieces of data to extract from the item. The results look like this:
This barely scratches the surface of what a data template can do visually. You are free to use absolutely any WPF feature in a data template, so you are by no means limited to text. Data templates can incorporate images, graphical elements, animations, or 3D content, for example. You can also add interactive controls, such as text boxes to allow data to be edited, or custom controls that provide whatever interactive behavior you would like.
As you can see, data templates provide a remarkably easy way to format lists of data returned by a service. You can apply them directly to plain XML data as this example does. You can also use them with objects, such as those returned by WCF web service wrappers.
Web Services and Object Data Binding
The ability to bind directly to XML can be useful, but often it can sometimes be more convenient to work with wrapper objects of some kind. If you are working with a web service that offers a WSDL definition, it is often possible to use tools to generate such wrappers. You can then use WPF's object-based data binding to bind to these objects instead of binding directly to the raw XML.
For example, eBay offer a WSDL definition of their web service API, which you can download from here: http://developer.ebay.com/webservices/latest/eBaySvc.wsdl (You need to sign up to their service in order to use the API, but the WSDL is freely downloadable.) eBay uses Java for it's back end, as also indicated by the server headers and error messages returned by their servers. Since it is a web service, the fact that it's implemented in Java places no constraints on the client-side technology. So you can import the WSDL into a .NET client.
You can use the web service support that has been available since the earliest versions of .NET. Alternatively you can use the new WCF (Windows Communication Foundation) tools introduced with .NET 3.0. Both technologies offer tools that will generate similar wrapper classes for the messages and associated types defined in the WSDL. One such type in the eBay web service API is UserType, which provides information about a user. The tool-generated wrapper for this extracts element values from the XML and presents them as .NET properties. We can then bind to these from WPF. The following markup binds a UI to some of the properties in a UserType. (This example assumes that some code somewhere in the application has obtained a UserType instance from the web service, and placed it into the UI's ‘data context', making it available for binding purposes.)
<Grid TextElement.FontSize="20">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="10" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="User ID:" />
<TextBlock Grid.Column="2" Grid.Row="0" Text="{Binding Path=UserID}" />
<TextBlock Grid.Column="0" Grid.Row="1" Text="Email:" />
<TextBlock Grid.Column="2" Grid.Row="1" Text="{Binding Path=Email}" />
<TextBlock Grid.Column="0" Grid.Row="2" Text="Feedback score:" />
<TextBlock Grid.Column="2" Grid.Row="2" Text="{Binding Path=FeedbackScore}" />
<TextBlock Grid.Column="0" Grid.Row="3" Text="Registration date:" />
<TextBlock Grid.Column="2" Grid.Row="3" Text="{Binding Path=RegistrationDate}" />
</Grid>
Note that instead of specifying "XPath=..." in the Binding expressions, we are now specifying "Path=...". This indicates to WPF that we expect the source data to be in an object's property rather than in XML form. The markup above presents user information as shown here:
The advantage of taking this object wrapper approach is that it makes it easier for the client to do more than just present the data. WPF applications usually consist of a mixture of markup and code. With the data from the web service extracted from the XML and wrapped in objects, the code can easily process this data and provide whatever client-side behavior the application needs.
Conclusion
We've examined two very simple examples that present a WPF front end on top of Java services. The main WPF-specific feature we've exploited is data binding, which provides a very convenient means of connecting data retrieved from a service to the UI. Like any rich client application, a WPF application can of course provides whatever client-side intelligence and behavior we would like. While these examples deliberately used extremely simple visuals to emphasize that WPF is more than just a pretty face, WPF has the potential to take the prosaic but useful world of data binding and ordinary Windows controls, and enhance it with visually rich presentation.
For other content related to .NET and Java integration scenarios, see also the special J+N content page on InfoQ.
About the author
Ian Griffiths is an independent consultant, developer, speaker, and author. He has written books on Windows Presentation Foundation, Windows Forms, and Visual Studio. He lives in London but can often be found on various developer mailing lists and newsgroups, where a popular sport is to see who can get him to write the longest email in reply to the shortest possible question. More information about what Ian is up to can be found on his blog at http://www.interact-sw.co.uk/iangblog/.