Tuesday, July 13, 2010

NullToBoolValueConverter for WPF

  You can enable or disable WPF elements based on if they are null or not. This is not supported, but you can create a simple value converter.
  /// <summary>
  /// Converts null to boolean.
  /// </summary>
  /// <remarks>
  /// If parameter is not specified or specified with null:
  /// if passed value is null then true is returned, otherwise false.
  /// If parameter is specified then inversion is done:
  /// if passed value is null then false is returned, otherwise true.
  /// </remarks>
  [ValueConversion(typeof(object), typeof(bool))]
  public class NullToBoolValueConverter : IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
      bool result = value == null ? true : false;
      if (parameter != null)
        return !result;
      return result;
    }

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


  This value converter allows me to bind to any property taking a boolean argument with the following syntax in XAML.
<local:NullToBoolValueConverter x:Key="NullToBoolValueConverter"/>

<ComboBox.IsEnabled>
  <Binding ElementName="TetsComboBox" Path="SelectedItem" Converter="{StaticResource NullToBoolValueConverter}" ConverterParameter="true" />
</ComboBox.IsEnabled>

2 comments:

  1. Hi,
    About code:
    value == null if a boolean value, so you can just write
    bool result = value == null;

    ReplyDelete
  2. You are right.
    Sometimes it is useful to look at the code with new eyes! :)

    This code:

    bool result = value == null ? true : false;
    if (parameter != null) return !result;

    return result;

    can be replaced with the following line

    return parameter == null ? value == null : !(value == null);

    ReplyDelete