May 18, 2011

WPF Binding not working? Check the Output Window

Took me a long time and hours of frustration troubleshooting WPF binding failures to finally find a silver bullet. Actually, this stuff is all over the place on the net, but for whatever reason, not mentioned in many WPF books.

If you are expecting to see a binding when you start your WPF application, but the value never changes, or is default, or the bound listview is empty when it should have data, check the output window in Visual Studio while you debug.

Bindings in WPF are best-efforts only by the framework. Not really sure why. I sometimes wish a giant unhandled exception error would show up instead of silent failure. Nevertheless...

Here's a sample error message you might find there.

Let's say you have the following XAML layed out and you're trying to bind a listview to a 'Parameters' ObservableCollection member of the control data context. But when you filled out the XAML, it was misspelled.

<DockPanel>
  <Label DockPanel.Dock="Top" Style="{StaticResource LayoutLabel}">Parameter Selection</Label>
  <Border  Style="{StaticResource LayoutBorder}">
    <ScrollViewer DockPanel.Dock="Bottom">
      <ListView View="{DynamicResource ParameterView}" ItemsSource="{Binding Path=Parametrs}"/>
    </ScrollViewer>
  </Border>
</DockPanel>

Now when you debug, the members of the 'Parameters' ObservableCollection don't appear in the listview. Go and check the output window and you might see this in the output window
System.Windows.Data Error: 39 : BindingExpression path error: 'Parametrs' property not found on 'object' ''OrderedEnumerable`2' (HashCode=57007955)'. BindingExpression:Path=Parametrs; DataItem='OrderedEnumerable`2' (HashCode=57007955); target element is 'ListView' (Name=''); target property is 'ItemsSource' (type 'IEnumerable')
Lots of gobbledygook, but clearly in this message WPF is complaining that binding cannot be made with a Parametr property. It shouldn't be too hard to find the trouble with this information.

More often than not, it's not a spelling mistake, but a plain mismatch between the object being searched by WPF and the binding path given.

Example being if the aforementioned control had a datacontext set to 'MyObject' but the class of 'MyObject' doesn't have a 'Parameters' property at all.

No comments:

Post a Comment