Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate wpf bindings are going to real properties?

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?

like image 679
Michael Hedgpeth Avatar asked Apr 17 '09 13:04

Michael Hedgpeth


2 Answers

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.

like image 44
John Myczek Avatar answered Nov 20 '22 16:11

John Myczek


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.

like image 73
Kent Boogaart Avatar answered Nov 20 '22 17:11

Kent Boogaart