Larry Beall: PHP & ASP.NET Who'da thunk it…

31Jul/091

Debugging WPF Bindings…

So the following question was posted on twitter earlier today.

So I take it that unit testing WPF bindings isn't an easy thing to do?

At ICC we tend to use what we consider a “Debug” value converter to make debugging bindings easier on ourselves.  Below is the source to such a value converter.

   1: using System;

   2: using System.Collections.Generic;

   3: using System.Linq;

   4: using System.Text;

   5: using System.Windows.Data;

   6:  

   7: namespace WpfApplication1

   8: {

   9:     public class DEBUG_Converter : IValueConverter

  10:     {

  11:         #region IValueConverter Members

  12:  

  13:         public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

  14:         {

  15:             return value;

  16:         }

  17:  

  18:         public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

  19:         {

  20:             throw new NotImplementedException();

  21:         }

  22:  

  23:         #endregion

  24:     }

  25: }

From here we we will put a break point in the Convert method, so that we can be sure that the binding is in fact firing and that the value we expect is showing up.  The thing to remember is that a binding in this scenario should fire atleast two times.  The first being the initial class instantiation, then the next one when a value is actually set.  If you get only one and the value coming in is null, it is most likely due to your implementation of INotifiyPropertyChanged not being correct.  Below is the source of the XAML that shows the binding with the debug converter applied.  I am also attaching the source of the example project that this code comes from.

   1: <Window x:Class="WpfApplication1.Window1"

   2:         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   3:         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   4:         xmlns:converter="clr-namespace:WpfApplication1"

   5:         Name="uiThis" 

   6:         Title="Window1" 

   7:         Height="300" 

   8:         Width="300"

   9:         >

  10:     

  11:     <Window.Resources>

  12:         <converter:DEBUG_Converter x:Key="_DEBUG_Converter" />

  13:     </Window.Resources>

  14:     

  15:     <Grid>

  16:         <TextBlock Text="{Binding MyString, ElementName=uiThis, Converter={StaticResource _DEBUG_Converter}}" />

  17:     </Grid>

  18: </Window>

One thing to remember is that this is just one approach and it is the first step we will normally take.  This will most likely help solve 50-60% of all cases.

Source Solution