WPF Snippet - Detecting Binding Errors

Skill

WPF Snippet - Detecting Binding Errors

Posted in:

Isn't it really annoying when WPF binding errors fail silently? The application compiles, the application runs, but nothing is working - all because of a silly typo in a binding somewhere. And then, once you realize it is a binding error (which is not always obvious), you have to drudge through the debug output trying to find that one line that says "System.Windows.Data Error ....". Even worse than that is the subtle binding error where the app still works, but maybe the text on some label isn't updating right, and you don't even notice the bug until weeks later.

If you are as annoyed by all that as I am, you have come to the right place. Today we are going to take a look at a simple way to make binding errors literally explode in your face (as MessageBoxes!). We are going to take a look at adding a custom trace listener to listen for binding errors and pop them up as a message box when they happen.

To do this, we have to create a custom trace listener - our own class derived from DefaultTraceListener. Trace listeners are behind almost all of the debugging/error reporting in .NET - it is where almost all the debug output comes from. Probably your most direct interaction with trace listeners comes from using Debug.WriteLine and Debug.Assert - trace listeners are used there to do the debug output and the message box in case of failure.

Our custom trace listener is actually a really simple chunk of code, so I'm just going to put it all here in one block and then walk through it.

using System.Diagnostics;
using System.Text;
using System.Windows;

namespace SOTC_BindingErrorTracer
{
  public class BindingErrorTraceListener : DefaultTraceListener
  {
    private static BindingErrorTraceListener _Listener;

    public static void SetTrace()
    { SetTrace(SourceLevels.Error, TraceOptions.None); }

    public static void SetTrace(SourceLevels level, TraceOptions options)
    {
      if (_Listener == null)
      {
        _Listener = new BindingErrorTraceListener();
        PresentationTraceSources.DataBindingSource.Listeners.Add(_Listener);
      }

      _Listener.TraceOutputOptions = options;
      PresentationTraceSources.DataBindingSource.Switch.Level = level;
    }

    public static void CloseTrace()
    {
      if (_Listener == null)
      { return; }

      _Listener.Flush();
      _Listener.Close();
      PresentationTraceSources.DataBindingSource.Listeners.Remove(_Listener);
      _Listener = null;
    }

   

    private StringBuilder _Message = new StringBuilder();

    private BindingErrorTraceListener()
    { }

    public override void Write(string message)
    { _Message.Append(message); }

    public override void WriteLine(string message)
    {
      _Message.Append(message);

      var final = _Message.ToString();
      _Message.Length = 0;

      MessageBox.Show(final, "Binding Error", MessageBoxButton.OK,
        MessageBoxImage.Error);
    }
  }
}

So first off, actually setting the trace listener. SetTrace here is a static method that takes a SourceLevel and TraceOptions. SourceLevel is essentially how much tracing to do. In our case here Error is a good value - otherwise we might get bombarded with message boxes. TraceOptions is a flag enum that says what types of information should be included in the trace. In general, I've found that you don't need any of the extra info to debug data binding errors, so I default it to None.

When SetTrace is called, we create an instance of our custom trace listener (unless our custom trace listener is already listening). Then we add it to the list of listeners on the DataBindingSource trace. PresentationTraceSources has a number of different traces, but today all we care about is the DataBindingSource. However, if you ever happen to be looking for other WPF debug information, this class is a good place to start.

Once our listener instance is added to the list, it will now be notified if there are any errors. This is where our overrides to the Write and WriteLine methods come in. The base methods for DefaultTraceListener do things like write debug output - but in this case we don't want to do that. In our case we want to show a message box with the error. However, because we don't want to be bombarded with message boxes, we only show one for every line written - we just accumulate the strings passed in to the Write call until a WriteLine call is made, at which point we display the whole error string.

And finally, as you might expect, the static method CloseTrace removes the trace listener from the list, so it won't be notified of errors anymore.

So how do we use this trace listener, and what does it show when there is an error? Well, below you can see a nice binding error waiting to happen:

<Window x:Class="SOTC_BindingErrorTracer.Window1"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="300" Width="300">
  <Button Content="{Binding ElementName=foo, Path=bar}" />
</Window>

The trace only needs to be set once, and then works for the entire application until it is closed. so in this case we set up the trace in the constructor for this widow:

public partial class Window1 : Window
{
  public Window1()
  {
    BindingErrorTraceListener.SetTrace();
    InitializeComponent();
  }
}

And now, when you start the application, you get the following very obvious error:

Binding Error Message

And that is it! Using this, now binding errors are as obvious as a regular old exception -and it is much less likely that one will slip in and stay in by mistake. You can grab the source for the custom listener below, if you would like to use it/modify it yourself. Hope you found this useful, and if you have any questions or comments drop them below.

Dennis
09/27/2009 - 20:45

What an excellent idea. Thank-you for sharing.

reply

lfsaunders
10/08/2009 - 17:39

I added a reference to this error tracer to the SOTC_DataGridExample tutorial, also on your site.

    public Window1()
    {
        SOTC_BindingErrorTracer.BindingErrorTraceListener.SetTrace();

      _GameData = new DataTable();
      _GameData.Columns.Add(new DataColumn("Game Name", typeof(string)));
      _GameData.Columns.Add(new DataColumn("Creator", typeof(string)));
      _GameData.Columns.Add(new DataColumn("Publisher", typeof(string)));
      _GameData.Columns.Add(new DataColumn("On Xbox", typeof(bool)));

When I executed the project I get an exception.

InvalidOperationException:
Dispatcher processing has been suspended, but messages are still being processed.

on line 54:

      MessageBox.Show(final, "Binding Error", MessageBoxButton.OK, MessageBoxImage.Error);

Here is the content of the "final" string:
System.Windows.Data Error: 39 : BindingExpression path error: 'Publisher' property not found on 'object' ''Object' (HashCode=27253481)'. BindingExpression:Path=Publisher; DataItem='Object' (HashCode=27253481); target element is 'TextBlockComboBox' (Name=''); target property is 'SelectedItem' (type 'Object')

What do you suggest?

reply

Jesse Chisholm
10/30/2009 - 22:04

I also just found this article, and like it very much.

To fix the exception on the call to MessageBox.Show have the Dispatcher put it back on the GUI thread.

Application.Current.Dispatcher.BeginInvoke(
  System.Windows.Threading.DispatcherPriority.Normal,
  new System.Windows.Threading.DispatcherOperationCallback(delegate { MessageBox.Show(...); return null; }), null);

-Jesse

reply

Andrew Nagel
05/14/2010 - 08:24

Great article, helped me identify two errors I didn't even know I had and much more quickly address a 3rd I was debugging within minutes of being installed.

reply

Jonx
05/27/2010 - 11:50

why is the dialog box only show when the program runs inside visual studio? when run outside the program runs without displaying any error...

reply

MattE
06/15/2010 - 12:54

I have the same question/issue as Jonx. The "Binding Error" messagebox is only displayed when my app is run under the VisualStudio debugger. If I run my debug build standalone, the messagebox is never shown. Anyone know why?

reply

The Reddest
06/15/2010 - 13:48

TraceListeners are only active under /d:DEBUG or /d:TRACE compilations. They work a lot like Debug.Assert(...) calls, which are only active under debug builds. Check out the DefaultTraceListener reference for more info.

reply

MattE
06/15/2010 - 16:24

Hi Reddest,
In my case, I am running a debug build with /define:DEBUG;TRACE turned on, but when I run that build directly (as opposed to running it within Visual Studio via Debug->Start new instance) I don't see the messagebox for binding errors. I DO see Debug.Assert dialogs though, so I don't think my problem is build settings. I looked at the DefaultTraceListener dox and didn't see anything relevant. I must be missing something but I can't figure it out...

reply

The Reddest
06/16/2010 - 07:49

I see, I definitely misunderstood the problem. Looks like you found a solution, though. Good find.

reply

MattE
06/15/2010 - 17:55

I found the reason why this doesn't work outside of Visual Studio:

The answer was here:
http://msdn.microsoft.com/en-us/library/system.diagnostics.presentationtracesources.aspx

Specifically:
---snip---
Debug tracing is only available when a WPF application is running in full trust mode.

In order to enable tracing, you first must set a registry key, then you must configure trace sources.

To create the registry key, set a “ManagedTracing” reg_dword value to 1 under “HKeyCurrentUser\Software\Microsoft\Tracing\WPF”.
---snip---

once I created the ManagedTracing registry setting, the output and messageboxes from the BindingErrorTracer started showing up when running my debug build standalone.

reply

sudheer v muhammed
03/17/2011 - 05:06

why u dont use visual studio output box for finding out the error . Whay you use this complex code for this simple debugging.

U can get output dialogue box after debugging go to view and click output in visual studio.

reply

Saravanan
10/18/2011 - 12:04

Handy piece of code. Thanks.

reply

Yak
02/22/2012 - 08:09

I got the same problem that the dialog box is not shown when i ran the application as a standalone (outside the visual studio debugger / F5).

I addded the line and it is working great for me (WPF version 4.0):

PresentationTraceSources.Refresh();

Before the listener registration : PresentationTraceSources.DataBindingSource.Listeners.Add(_Listener);

Yak

reply

Anonymous
03/30/2012 - 11:26

excellent! thanks

reply

Oscar
03/30/2012 - 11:33

excellent!
you can fix the message by doing this:

public override void WriteLine(string message)
{
_Message.Append(message);

var final = _Message.ToString();
_Message.Length = 0;

ShowDialogOK(final , "Binding Error");
}

private bool ShowDialogOK(string msg , string msg1)
{
MessageBoxResult messageBoxResult = MessageBox.Show(msg , msg1 , MessageBoxButton.OK , MessageBoxImage.Information);
if(messageBoxResult == MessageBoxResult.Yes)
return true;
return false;
}

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.