Skip to main content

...

....

C# WPF Snippet - Detecting Binding Errors [Beginner]


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. 


Source Files:

Comments

Popular posts from this blog

C# Snippet - Shuffling a Dictionary [Beginner]

Randomizing something can be a daunting task, especially with all the algorithms out there. However, sometimes you just need to shuffle things up, in a simple, yet effective manner. Today we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application. The tricky thing about ordering dictionaries is that...well they are not ordered to begin with. Typically they are a chaotic collection of key/value pairs. There is no first element or last element, just elements. This is why it is a little tricky to randomize them. Before we get started, we need to build a quick dictionary. For this tutorial, we will be doing an extremely simple string/int dictionary, but rest assured the steps we take can be used for any kind of dictionary you can come up with, no matter what object types you use. Dictionary < String , int > origin = new Dictionary < string , int >();

C# WPF Printing Part 2 - Pagination [Intermediate]

About two weeks ago, we had a tutorial here at SOTC on the basics of printing in WPF . It covered the standard stuff, like popping the print dialog, and what you needed to do to print visuals (both created in XAML and on the fly). But really, that's barely scratching the surface - any decent printing system in pretty much any application needs to be able to do a lot more than that. So today, we are going to take one more baby step forward into the world of printing - we are going to take a look at pagination. The main class that we will need to do pagination is the DocumentPaginator . I mentioned this class very briefly in the previous tutorial, but only in the context of the printing methods on PrintDialog , PrintVisual (which we focused on last time) and PrintDocument (which we will be focusing on today). This PrintDocument function takes a DocumentPaginator to print - and this is why we need to create one. Unfortunately, making a DocumentPaginator is not as easy as

C# WPF Tutorial - Implementing IScrollInfo [Advanced]

The ScrollViewer in WPF is pretty handy (and quite flexible) - especially when compared to what you had to work with in WinForms ( ScrollableControl ). 98% of the time, I can make the ScrollViewer do what I need it to for the given situation. Those other 2 percent, though, can get kind of hairy. Fortunately, WPF provides the IScrollInfo interface - which is what we will be talking about today. So what is IScrollInfo ? Well, it is a way to take over the logic behind scrolling, while still maintaining the look and feel of the standard ScrollViewer . Now, first off, why in the world would we want to do that? To answer that question, I'm going to take a an example from a tutorial that is over a year old now - Creating a Custom Panel Control . In that tutorial, we created our own custom WPF panel (that animated!). One of the issues with that panel though (and the WPF WrapPanel in general) is that you have to disable the horizontal scrollbar if you put the panel in a ScrollV