Sunday, June 17, 2007

NullToBooleanConverter for WPF

I have found it useful to enble or disable WPF elements based on if they are null or not. This is not supported out of the box so I need a simple value converter. The simple value converter has been updated to support all things that has a Count property.

public class NullToBooleanConverter : IValueConverter
{
   public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
   {
       if (value == null) return false;
       PropertyInfo propertyInfo = value.GetType().GetProperty("Count");
       if (propertyInfo != null)
       {
           int count = (int) propertyInfo.GetValue(value, null);
           return count > 0;
       }
       if (!(value is bool || value is bool?)) return true;
       return value;
   }

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

The simple value converter above allows me to disable any element with the following syntax in XAML.


<local:NullToBooleanConverter x:Key="nullToBooleanConverter"/>

<Button IsEnabled="{Binding Path=Owned, Converter={StaticResource nullToBooleanConverter}}" Content="Tapir"/>

The converter can of course be used for any other property taking a boolean argument.

No comments: