Search code examples
wpfsyntaxbindingdeclarative

WPF binding declarative syntax: enable a GroupBox when a checkbox is NOT set


I'm a WPF newbie, so pardon me in advance if this is a dumb question. I've got syntax for enabling a GroupBox if a checkbox is checked, which works fine:

IsEnabled="{Binding ElementName=cbIsDeceased, Path=IsChecked}"

But what I need is to flip the polarity. I need IsEnabled to be true when the checkbox is NOT checked and vice versa. Is there a declarative way to get that?

Thanks.


Solution

  • You have to add a converter to invert the boolean value. In XAML, define the resource for the converter and add it to the binding:

    IsEnabled="{Binding ElementName=cbIsDeceased, Path=IsChecked, Converter={StaticResource InverseBooleanConverter}"

    And to spare you some time, I give you my version of the converter, which is extremely simple :)

    /// <summary>
    /// Converts a boolean to its opposite value
    /// </summary>
    [ValueConversion(typeof(bool), typeof(bool))]
    public class InverseBooleanConverter: IValueConverter
    {
        #region IValueConverter Members
    
        public object Convert(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            if (targetType != typeof(bool))
                throw new InvalidOperationException("The target must be a boolean");
    
            return !(bool)value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    
        #endregion
    }