Thursday, February 7, 2008

Debugging databindings

Sometimes you databind and nothing happens.  Your world is totally empty and there's no databind trace spew in the output window. 

If you want to have a look at the data as it is coming through, I just learned a handy trick for doing this:  make your own binding converter. 

When the binding is being processed, it can use a converter to change the data from one type to another (e.g. a Color to a SolidColorBrush).  This means that the original data passed in appears in the IValueConverter.Convert method.

If you create a converter that does nothing, you can observe the data that goes through.  This can be handy to determine if you've got the right object in your databinding.

debugdatabinding

In the sample below, we can verify if there is a red brush coming through the Button.Background property by putting a breakpoint in the DebugConverter.Convert method.

<Window ...
    xmlns:local="clr-namespace:WpfApplication1"
    Title="Window1" Height="300" Width="300">
    <Grid Name="rootGrid" Background="Red">
        <Grid.Resources>
           <local:DebugConverter
                    
x:Key="_debugConverter"/>
        </Grid.Resources>
        <Button
            Background="{Binding ElementName=rootGrid, Path=Background, Converter={StaticResource _debugConverter}}"
            />
           </Grid>
</Window>

 

public class DebugConverter : IValueConverter {
     public object Convert(object value, 
       
Type targetType, object parameter,
       
System.Globalization.CultureInfo culture) {
         

         return value; // <--insert breakpoint here
      }

      public object ConvertBack(object value, 
       Type targetType, 
       object parameter, 
       System.Globalization.CultureInfo culture) {
          return value;
      }

  }

No comments: