views:

128

answers:

2

I would like a simple way to ensure that all bindings I've declared in my xaml files go to real properties. Even better, I'd like to instantiate my wpf window in a unit test and call a method to ensure that the bindings are correct.

Unfortunately, wpf doesn't even throw an exception if I have something wrong. That leaves me the burden to "discover" problems during a QA phase.

Does anyone know of a way I can better validate my bindings?

+3  A: 

A suboptimal way would be to search through the visual tree for all dependency properties, and then check:

var bindingExpression = BindingOperations.GetBindingExpressionBase(dependencyObject, dependencyProperty);

if (bindingExpression != null)
{
    var status = bindingExpression.Status;
}

If the status is Unattached then the expression hasn't resolved.

Of course, you wouldn't want to do this in a production app, but it might make sense in a debug or integration test scenario.

HTH, Kent

Kent Boogaart
A: 

Data binding errors show up in the Visual Studio Output window. For example, say I want to bind a TextBlock to the Title property of a Window but I mistype "Title" as "Ritle". I will see this in the output window:

System.Windows.Data Error: 39 : BindingExpression path error: 'Ritle' property not found on 'object' ''MessageWindow' (Name='Window')'. BindingExpression:Path=Ritle; DataItem='MessageWindow' (Name='Window'); target element is 'TextBlock' (Name='WindowTitle'); target property is 'Text' (type 'String')

You can get more control over how these messages are reported by using Trace Sources. This article by Bea Stollnitz describes this in greater detail.

John Myczek
I hear what you're saying, but that doesn't really validate your bindings. It just provides debug info that the developer has to scrutinize. I think an attempt to write a TraceListener that throws when it "discovers" a binding error would be rather fragile, given that it would have to parse messages that could change at Microsoft's whim. Probably better than nothing, though.
Kent Boogaart