Search code examples
wpfxamlbinding.net-4.0

How to locate the source of a binding error?


How can I figure out what line of xaml contains the troublesome binding When my debug output is full of lines like the following:

System.Windows.Data Error: 5 : Value produced by BindingExpression is not valid for target property.; Value='UW.Entities.ProgramModel.UWProgram' BindingExpression:Path=; DataItem='RuntimeType' (HashCode=24995901); target element is 'DataGridCollectionViewSource' (HashCode=60976864); target property is 'Source' (type 'Object')

I don't know how to interpret this in a way that can let me find the responsible line of xaml. I can't even figure out what xaml file the error is coming from. Is there some way to get more information when these errors occur?

'UW.Entities.ProgramModel.UWProgram' is just a type - I don't know what the object being bound to is. I also have lots of DataGridCollectionViewSources in various bits of xaml, all who's property 'Source' is bound to something which may or may not have that type (again - no easy way to tell).


Solution

  • If you do not know which binding fails

    I would use the Snoop utility for this purposes. In short - at the top-left corner above the visual tree, you'll find a drop-down list which allows filtering visuals, just select Visuals with binding Error. See online documentation for more details.

    If you know which binding fails

    Sometime you know which binding fails but was not able to find a source fo the problem since binding is pretty tricky, for instance TemplateBindings, bindings which refer to a DataContext of another control, etc.. I found helpful putting a TextBlock which Text property is bound to the same binding source in this way you can see what exactly bound since TextBlock will display a type name of a bound object.

    For instance you have following failed binding:

    <ItemsControl ItemsSource="{Binding Parent.DataContext.ActiveItem.DataContext}" />
    
    <!-- See what is bound, if failed - try previous level  -->
    <TextBlock Text="{Binding Parent.DataContext}" />
    <TextBlock Text="{Binding Parent.Inner.Items}" />
    <TextBlock Text="{Binding Parent.Inner}" />
    

    Useful links: