Tips on how to debug and learn about WPF

March 29, 2007

Debugging WPF applications can be a tough challenge, especially for people just starting off with the platform.  Not only is it tough to debug WPF code, but just figuring out how to build what you dream up can be a challenge.  The point of this blog post is to make it easier to find information about how to design WPF applications, and how to debug them efficiently.

Getting info and help

Use Google (duh).  I’m amazed at how many questions I see posted around the web asking how to do something in WPF, whose answer is immediately obvious after a simple Google search.Visit Microsoft’s WPF Forum and use the Search page.  You might be surprised at how many times your question has been asked and answered there.  Be sure to use the Advanced Search Options and filter on the WPF Forum:

Search the WPF Forum

If your searches come up empty, you should post your question on the WPF Forum.  There are many helpful people who monitor that forum.  However, before posting your first question there, be sure to read this post by Rob Relyea about forum etiquette.

The MSDN documentation is your friend.  If you want to have a really fast and helpful friend use your local copy of the help files, which was installed during installation of the Windows SDK.  If you don’t know what I’m referring to, go Start | All Programs | Microsoft Windows SDK | Windows SDK Documentation.

Read books about WPF.  I have found ‘WPF Unleashed’ and ‘Applications = Code + Markup’ to be great. 

Read peoples’ WPF blogs.  For a great listing of WPF blogs, check out Tim Sneaths’ WPF blog roll here.

Check out all of the great resources on  That site has a lot of samples, demos, links to reading material, etc.  It’s definitely a site to put in your Favorites list. is another gem.

CodeProject articles about WPF are, of course, a great resource.  You can view a list of all their WPF articles here.

Debugging tips and tricks

Inner Exceptions reveal the answer to so many runtime exceptions that it’s barbarically annoying (yet helpful).  I often see questions where folks ask why their WPF app is blowing up, and the answer lies in an InnerException one or two levels deep. In case you have no idea what I’m talking about, allow me to explain.  The standard .NET Exception class has a property called InnerException.  That property can reference another Exception, whose message might contain an explanation of why the error occurred.  The InnerException itself might have a reference to its own InnerException, and so on. 

As exceptions are thrown, handled, and re-thrown in the .NET Framework exceptions can be chained together to provide a “history” of the error.  Many WPF exceptions have several nested InnerExceptions, each of which might contain a useful piece of evidence you can use while debugging.  Usually the deepest (most nested) exception is the one which explains what the real problem is.When you are running an application in debug mode and an exception is thrown, you will first be confronted with Visual Studio’s exception dialog:

Open the exception dialog

After clicking the View Detail link, you can dig into the guts of the exception and check out what actually went wrong:

Viewing nested InnerExceptions

There is a fantastic free utility, by Pete Blois, called Snoop which you should download if you want to do any serious WPF debugging.  Snoop is the best WPF debugging tool out there so far.  Get it.  Not only will it show you the entire element tree of a WPF user interface, but it will let you see many other things such as: what routed events have been raised, data binding errors, a preview of any element, a zoomed view of an element, and more.

A while back Mike Hillberg blogged about the TraceSources built into WPF.  I’ve used this for debugging and educational purposes, and found it to be useful for both. As he mentions, the data binding source is “on” by default, as you can see when viewing the Output window in Visual Studio while debugging a WPF app.

As always, get Lutz Roeder’s Reflector.  That is the best .NET utility application of all time.  It will decompile any .NET assembly (including the WPF assemblies) and allow you to read how they work, in the high-level language of your choice.  If you don’t already have it, what’s wrong with you? 🙂  Also, there is a BAML-to-XAML converter add-in for Reflector you can use to inspect the resources a WPF assembly has embedded in it.

Create a dummy value converter and use it, often.  If you ever want to know what value a Binding is passing from one object to another, inject your dummy value converter into it and set a breakpoint.  I’ve used this little trick a million times and it never fails to help.  Here’s the basic gist:

Dummy ValueConverter

Another useful trick for debugging is to use the DependencyPropertyHelper’s GetValueSource static method.  It takes in a DependencyObject and a DependencyProperty, and returns a value indicating what actually set that property (with regards to the rules of precedence associated with DPs).

If you have any other useful tips that belong in this blog post, feel free to leave me a comment with your ideas.


WPF uses HWNDs, but sparingly.

March 26, 2007

A fellow by the name of Patrick Sears asked me a question about the relationship between WPF and HWNDs.  I’m posting the answer here, for all to read.


In your intro to WPF, you state:[^]

“Another benefit of using vector graphics is it works well with high-resolution displays; something which is becoming a problem for the antiquated HWND technology as the resolution of display units improves.”

I read something to the same effect on another blog, basically that WPF is not HWND based. What is the basis for this statement? Windows (Vista included) itself is still HWND based, is it not? How can the operating system fundamentally render a window without an HWND?


The OS can’t render a window without an HWND.  WPF uses HWNDs very sparingly.  One prime example of HWNDs in WPF is the Window class.  It is a normal Windows window…receiving WM_WHATEVERs just like any other window.

Saying that WPF is not based on HWNDs has meaning within a window.  In Win32, MFC, WinForms, etc. every pixel in a Window was “owned” by a control.  Since a control was really just another window (and a window is an HWND), one could say that every pixel was owned by one and only one HWND.  That means that the graphical rendering of a Window’s client area was pretty much limited by the rendering capabilities of an HWND.  That does not include things like transformations, animations, occlusion (one pixel being rendered as a combination of two or more overlapping visual elements), etc.

WPF’s vector based rendering system introduces an array of rendering capabilities which HWNDs never even dreamed of.  Since pretty much every visual element in WPF is rendered via the vector graphics system (one notable exception being the Popup class), an entire WPF UI can make use of those features out-of-the-box.

The WPF Challenge winners

March 22, 2007

The winners of The WPF Challenge have been determined.  It was difficult to pick three winners, because many of the submitted applications were very impressive.  Here’s the glory story:

First Place Quixotry by Johnny Turpin

Application: Quixotry is a beautifully designed game, similar to Scrabble.  The UI is elegantly simple and intuitive.  It provides smooth drag-drop effects for the letter tiles, which is a nice touch.  I feel that this application makes use of WPF in an elegant and simple way. The game also has an artificial opponent to play against.

Winner: Johnny Turpin is a multi-dimensional software engineer who has developed an interest and expertise in software design for the 10′ experience. He is currently working for Industry Next, a technology and design firm, where he is a Senior Engineer exploring the latest application frameworks and design patterns and how to apply them to create compelling interactive entertainment applications. He has held previous positions at Apple Computer where he worked in the Video Architecture Group and Minerva Networks where he championed the development of IP Television applications. He can be found around the New York area playing in the band Seems So Bright and enjoys the occasional competitive game of foosball and tennis.

Second PlaceWPF Physics (desktop version) by Chris Cavanagh

Application: Cavanagh’s WPF Physics desktop application is a very fun and dynamic UI, which uses a physics engine he wrote.  The animations are very slick and realistic.  This application demonstrates that WPF can really shine in unexpected ways.

Winner: I’m a .NET web application developer based in south eastern Minnesota.  I moved here (with my wife Nicola and three awesome kids) from England in 2004 with a background in C, C++, Delphi and .NET.  It’s been one heck of a ride since then!  I spend most of the week knee-deep in ASP.NET and (recently) Flex development.  I started following Avalon pretty early and was pumped when WPF was finally released (no more breaking updates – yay!).  I’m your typical geek who codes through the day, then codes the rest of the time too (probably in my sleep also; I’ve always got some crazy hobby project on the go).  My interest in integrating physics engines with WPF probably comes from my past obsession with 3D graphics coding and games that let me blow stuff up.  FYI I’ve got an all-C# physics engine almost ready to roll (based on the Bullet engine) and some funky stuff with BSP trees; hopefully you’ll see that on my blog sometime soon!

Third PlaceRSS Reader by Gavrilovici Corneliu

Application: RSS Reader really stands out visually.  It is a simple tool which has a great look and feel.  It has nice visual effects when changing the category of blogs to view.  This application seems to be something that one wouldn’t see in anything HWND based, so it definitely is a “WPF app” worth checking out.

Winner: My name is Corneliu Gavrilovici and I was born in Romania, Cluj Napoca, on the 2nd of July 1984. I’ve graduated a technical high school and afterwards I applied to the Computer Science University and I got accepted. I am now in my third year of study and I also work as a programmer in a well respected company.(this is their site ) I had an interest regarding computers and programs since I was a teenager and therefore I started programming with the will of fulfilling my needs and dreams. I thank you for contacting me and I hope this brief bio gives you an idea on how I am and do.

Notable Mentions
Three judges were involved with choosing the winners of The WPF Challenge.  We did not all agree on which apps were the best (I had to ultimately make that very difficult choice).  Here are the apps that were picked as potential winners, but did not make it into the final list.

Chart and Lens Panel by John Stewien

Sticky Spaces by Forrest Miller

You can view all of the submitted applications on this page

The Judges

Here are the fellows who helped decide which apps won the competition.

Jordan Nolan,
I’m a former Infragistics Windows Developer and software consultant in the Boston area.  I’ve been extolling the wonders and virtues of WPF for a couple of years now to anyone who will lend an ear.  When I’m not blissfully working with .Net I can usually be found indulging my passion for great wine, scotch and cognac.

Nick Thuesen
I’m currently a WPF developer for the New York Times.  I’ve spent the last year and a half building the Times Reader application.  Lately, I’ve been eating, sleeping and thinking WPF.  In my spare time I’m your typical sarcastic geek who writes code in his spare time.  (This is when I’m not in a heated philosophical discussion on why Batman could possibly take Superman in a battle royale.)  I have a blog where I write posts about subjects I pretend to know a lot about.  You can find it at

Josh Smith
I love four things: my girlfriend Denise, the music of J.S. Bach, fine liquors (particularly scotch), and WPF.  I’ve been playing classical piano since I was five years old, and programming since around nine or ten.  I’ve known Jordan for years now, and worked with him at two different companies.  I’ve gotten to know Nick for about one month so far while working with him at The New York Times on Times Reader.  Oh yea…I recently just discovered how ridiculously funny South Park is.  🙂

The winners of The WPF Challenge…

March 20, 2007

…will be announced soon.  The judges are still trying to decide which of the submitted apps are the grandest of them all.  I intend on publishing the long awaited List of Winners soon. 🙂

Until then, go about your daily life as if nothing extraordinary is brewing…

Updating the UI when binding directly to business objects that are modified

March 18, 2007

This morning I woke up to find a rather curious question posted to the WPF Forum.  A fellow by the name of Waseem Sadiq is binding a ContentPresenter directly to a business object (i.e. not to properties on the object) and using the ContentPresenter’s ContentTemplateSelector to load the appropriate data template at runtime. 

I think the basic idea is that an entity in his system which is not “started” will be displayed as a “Start” button, and an entity which has already “started” will be displayed as a “Stop” button.  Each button’s Command is set to a custom command to “start” or “stop” the entity, and the button’s CommandParameter is bound to the entity itself.  Binding the CommandParameter property to the entity makes it easy to access it when the command is executed.  For more details on his situation, read the post here.

The problem with the situation is that when a bound business object has a property modified, the property change notification is not noticed by the ContentPresenter which displays that object.  The business object class implements INotifyPropertyChanged, but since the ContentPresenter is bound directly to the object (and not bound to a property on the object) its PropertyChanged event is irrelevant to the Binding. 

Suppose that an entity which has “started” is suddenly “stopped” by some part of the application.  Let’s say that the object’s IsRunning property is set from true to false.  Since the ContentPresenter does not notice any property changes on the object, the entity’s button will continue to display “Stop” instead of changing to display “Start.”  That’s a bug in the application (not the platform).  The million dollar question is: how can one fix it?

The answer I came up with was to wrap the business object in a wrapper class which exposes it as a property.  That wrapper class also implements INotifyPropertyChanged and raises its PropertyChanged event when the wrapped business object’s PropertyChanged is raised.  You then create a value converter which takes in a business object and emits a wrapper around it.  The value converter is then used in the DataContext binding of a top-level panel in the business object’s DataTemplate.  Thus, all elements in the DataTemplate should bind to the public property on the wrapper which exposes the actual business object to display.

Here’s the source code for my demo app: Displaying Changes to Business Objects (change the file extension from .DOC to .ZIP then decompress).  The demo app displays Foo objects (of course) and also a Button for each Foo.  If the Foo object’s Bar property is even, that Foo’s button reads “Make Odd.”  If it’s Bar property is odd, the button reads “Make Even.”  Clicking a Foo’s button will execute a command which modifies the Bar property on that Foo instance.  The wrapper class in the demo is called BusinessObjectHolder.

Animated Filtering of ListBoxItems

March 13, 2007

I have a simple objective: to apply a filter to a ListBox’s data source and have the filtered out items “fade away.”  I also want items that are filtered back into the ListBox to “fade into view.”  I thought it would be a straightforward affair.  I was very wrong.  This blog post is a big one, so go grab a snifter of Laphroaig 10 Year Cask Strength and put on some J.S. Bach harpsichord music (or whatever keeps you afloat) and then we’ll get started…

Before I go any further, if you aren’t interested in reading about all the issues that exist around implementing this functionality, you can download the source code here: Animated ListBoxItem Filtering  (change the file extension from .DOC to .ZIP).  Keep in mind, I have not yet found what I consider to be a satisfactory way to implement this. 

It was very easy to throw together some dumb code that did the trick, in a Window’s code-behind.  Unfortunately that is a terrible make-shift solution, because it is not at all reusable (unless the prospect of copy-and-pasting the same chunk of code into many Window code-behinds doesn’t make you nauseous – in which case I hope I never have to work with you).  It would be much better to put that fading animation logic into a ListBox subclass, so that it’s a breeze to make use of it later on.  That’s where the trouble begins…

WPF has support for filtering a collection of items which are displayed, via the CollectionView.Filter property.  Filter is a public property of type Predicate<object> which allows you to give a Yea or Nay regarding which data objects should be displayed in the UI.

You might be thinking that the Filter property would make my task a snap.  That’s what I thought when I first started looking into this issue.  It turns out that using the Filter property is actually detrimental for implementing this feature.  Here’s the deal…

When you set the Filter on a CollectionView (in my case, a ListCollectionView), a bunch of things happen.  The basic gist is that the CollectionView experiences a severe earthquake, sends shockwaves to any control bound to its list of items, and, when it’s all done shaking and quaking, you get notified that all Hell broke loose.  More specifically, the CollectionView verifies its list of items, sends a message to my ListBox indicating that the whole list was reset, and that causes the ListBox to create all new ListBoxItems for the “new” list of data.

Notice that at no point in time does the CollectionView alert the outside world that the list is about to be reset, before it happens.  Also, the ListBox does not have any suitable method/property to override which alerts you before its items are about to be thrown away and recreated (at least none that I could find).  The ListBox has a bunch of virtual methods that let you know after the items have changed (such as OnItemsChanged) but that doesn’t help us when we need to animate an item just before it is removed.  As far as I can tell, there is no event or virtual method which can be used on either the CollectionView or ListBox which gives you a “heads up” about that.

My make-shift solution (which is available to download toward the top of this article) does not at all use the Filter property of CollectionView.  Instead, when it’s time to apply a filter I manually iterate over the ListBox.Items property, get each ListBoxItem, and then fade it away if necessary.  This sucks for a variety of reasons:

1) The data filtering should be done at the data source level, not the control level.  This is especially important if more than one list control was bound to the same CollectionView, since they should all only show the “filtered in” items.  By filtering the items on the control level, you would have to manually filter each bound control whenever the filter changes.
2) The “filtered out” items are still in the ListBox’s Items collection.  This is weird because the items are not visible in the ListBox.
3) As mentioned previously, the logic for filtering the items is a Window’s code-behind.  This really stinks because it is not at all easy to cleanly reuse elsewhere.
4) Other reasons I have not thought of at the moment…

To be honest with you, I don’t know what the ideal solution to this problem is.  I’ve thought about it a lot, and have not yet come up with a really good way to solve this problem.  If the WPF team were to add some event which let you know that the list of items is about to change, I don’t know if it would help at all.  Since animations are asynchronous, by the time those animations got started the ListBoxItems being animated would be thrown away and new ones created.

The only solution that I’m halfway happy about is putting this logic into a ListBox subclass and exposing three new properties: Filter, ItemsFilteredIn, and ItemsFilteredOut.  That approach still suffers from having the filtering logic not on the data source level, but at least it would be encapsulated.  If I end up implementing that control, I’ll post an article about it on the CodeProject.

If you have any good ideas/suggestions about how to implement this in a better way, please let me know.

It is time to pick the winners

March 12, 2007

The final day for new submissions to The WPF Challenge has come and gone.  I’m happy to announce that the competition has 12 contestants, and 14 applications were submitted!  Most of the submissions are really cool, so it will be tough to pick three winners.  However, myself and two others will undertake that arduous task sometime in the next week or so.  Shortly thereafter I will be post an extensive blog entry which reviews the winning applications and their creators.

If you want to check out all of the submissions, they are listed here.

How to programmatically click a button

March 9, 2007

Back in WinForms it was really easy to simulate a user clicking a Button, you just call a Button’s PerformClick method.  For some reason the WPF Button does not have that method.  It turns out that you need to enter into the automation world to accomplish this task.

Here’s the code:

ButtonAutomationPeer peer =
  new ButtonAutomationPeer( someButton );

IInvokeProvider invokeProv =
  peer.GetPattern( PatternInterface.Invoke )
  as IInvokeProvider;


A cup of coffee and a side of XAML

March 7, 2007

As I sipped my morning coffee I threw this stupid thing together in XamlPadX.  Notice how the Margin property on the various shapes is used to achieve relative positioning of the eyes and mouth.  Of course, the callout full of XAML was added in later using SnagIt. 😉

mr xaml

WPF goes green…another contestant grinds his axe

March 5, 2007

With only one week left for submissions to be entered into The WPF Challenge, a chap by the name of Dave Biggar has entered the ring.  He submitted an XBAP application which displays photos and information about trees in Ottawa, Canada.  You can view this neat creation here and the introduction here.

Keep in mind, ladies and gentleman, time is running out.  The final submission date is Monday March 12, 2007.  That Monday ends according to the GMT timezone, because that’s the timezone which my blog uses.  Late submissions are immediately disqualified.  So, if you’re gonna give it a shot, now’s the time to do it! 🙂