Sunday, September 6, 2009

Wpf : what you really need to understand first is databinding

Learning the basics layout of a WPF program is not that difficult, I mean how to place basic controls like buttons, labels, textboxes, ... Making a great interface is something else, but that requires other skills, UI designer skills. But what I think is the most important part to understand early is the binding. This is the part of the course / book that I advise you to spent the most time on. I've lost too many hours finding out why my data was not visualised :
° Compilation : 0 warnings, 0 errors
° Setting a breakpoint on the method that delivered the data : breakpoint was never hit
° Output window did not show any errors, warnings
° Settings the ItemsSource in code behind works like a charm, so the data providing method works !

Below is an example program, see if you can find the mistake.
<Window x:Class="Damn.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lc="clr-namespace:Damn"
Title="Window1" >

<Window.Resources>
<ObjectDataProvider x:Key="CCNetProject"
ObjectType="{x:Type lc:CCNetJiraDataProvider}"
MethodName="GetProjects"
/>

<DataTemplate x:Key="CCNetProjectTemplate" >
<StackPanel Orientation="Horizontal" Background="LightBlue">
<Label Content="{Binding Key}" Width="200"/>
<Label Content="{Binding Description}" />
</StackPanel>
</DataTemplate>
</Window.Resources>

<StackPanel DockPanel.Dock="Top" Orientation="Vertical">
<ListBox x:Name="lstY"
ItemsSource="{Binding StaticResource CCNetProject}"
ItemTemplate="{StaticResource CCNetProjectTemplate}"/>
</StackPanel>

</Window>

So this has kept me busy for some hours, ok the mistake was mine, but how could I have found the error more easily?
I can not set a breakpoint in XAML, and setting a breakpoint in the method did not get hit. How do other WPF programmers pinpoint these kind of problems. For me this is a serious problem / shortcoming in Visual Studio. Any body knows some tips/tricks ?

5 comments:

  1. I found a blog that has a solution
    http://blog.wouldbetheologian.com/2009/07/why-wpf-databinding-is-awful-technology.html

    So I'm not the only guy finding this difficult, and judging from hiw writing style, he is NOT pleased with WPF also.

    ReplyDelete
  2. Found a better implementation of the binding errors detection.
    http://www.switchonthecode.com/tutorials/wpf-snippet-detecting-binding-errors
    This requires a 1 extra line, and not adjusting the binding expression itself. Much easier to swithc on and off.

    ReplyDelete
  3. OK - I give up!

    What is wrong with the WPF?

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Hi, the correct binding is :
    < ListBox DockPanel.Dock="Top"
    ItemsSource="{Binding Source={StaticResource AllProjects}}"
    ItemTemplate="{StaticResource CCNetProjectTemplate}"
    /&gt>;

    ReplyDelete