WPF Binding Errors

I find the binding aspect of WPF to be very powerful.  There’s one part that I found challenging. If the binding wasn’t just right, the problem wouldn’t be obvious.  If I make a typo when binding to a property, I like it to be painfully obvious.  So, the project now displays a message box if there was a binding issue.
The BindingErrorTraceListener class watches for any trace messages that meet my binding error criteria and displays a message box.
public class BindingErrorTraceListener : DefaultTraceListener
{
    public static void AddDefaultTrace()
    {
        AddTrace(SourceLevels.Error, TraceOptions.None);
    }

    public static void AddTrace(SourceLevels level, TraceOptions options)
    {
        var listener = new BindingErrorTraceListener {TraceOutputOptions = options};
        PresentationTraceSources.DataBindingSource.Listeners.Add(listener);
        PresentationTraceSources.DataBindingSource.Switch.Level = level;
    }

    public override void WriteLine(string message)
    {
        base.WriteLine(message);

        if (message == null) return;
        if (!message.StartsWith("BindingExpression path error")) return;

        MessageBox.Show(message, "Binding Error", MessageBoxButton.OK,
                        MessageBoxImage.Error);
    }
}
When we enter the window, we have to add our listener.
 BindingErrorTraceListener.AddDefaultTrace();
For testing purposes, I added a label that points to a nonexistent property on the view model.
<Label Content="{Binding MainLabel}" />
    public class LandingPageViewModel
    {
    }
Once everything is connected, an invalid binding will be very obvious because a message like this will appear.
WCFBindingError

Leave a Reply

Your email address will not be published. Required fields are marked *