Enhanced BooleanToGrayscaleConverter

Topics: Feature requests
Aug 27, 2012 at 5:40 AM

Hi Geert,

maybe you'll like this enhanced version of a BooleanToDouble converter.
I use it to bind Opacity properties to booleans.

Regards, alex.

 

namespace Catel.Windows.Data.Converters
{
    using System;

#if NETFX_CORE
    using global::Windows.UI.Xaml.Data;
#else
    using System.Windows.Data;
#endif

    /// <summary>
    /// Converts a boolean to a grayscale saturation value. If the input is <c>false</c>, this converter will
    /// return <c>0</c>, otherwise <c>1</c>.
    /// </summary>
#if NET
    [ValueConversion(typeof (bool), typeof (double))]
#endif
    public class BooleanToDoubleConverter : ValueConverterBase
    {
        /// <summary>
        /// The value a input value of false will be converted to.<br />
        /// Defaults to 0
        /// </summary>
        public double FalseResult { get; set; }

        /// <summary>
        /// The value a input value of true will be converted to.<br />
        /// Defaults to 1
        /// </summary>
        public double TrueResult { get; set; }

        public BooleanToDoubleConverter()
        {
            FalseResult = 0;
            TrueResult = 1;
        }

        /// <summary>
        /// Modifies the source data before passing it to the target for display in the UI.
        /// </summary>
        /// <param name="value">The source data being passed to the target.</param>
        /// <param name="targetType">The <see cref="T:System.Type" /> of data expected by the target dependency property.</param>
        /// <param name="parameter">An optional parameter to be used in the converter logic.</param>
        /// <returns>The value to be passed to the target dependency property.</returns>
        protected override object Convert(object value, Type targetType, object parameter)
        {
            if (!(value is bool))
            {
                return 1d;
            }

            return ((bool)value) ? TrueResult : FalseResult;
        }
    }
}

 

Usage:

<UserControl.Resources>
    <catel:BooleanToDoubleConverter x:Key="okToOpacityConverter" TrueResult="1.0" FalseResult="0.5" />
</UserControl.Resources>

<GroupBox Header="Something to display"
          Opacity="{Binding Path=Model.ContentIsOk
                   Converter={StaticResource okToOpacityConverter}}">
  <Label Text="content to display" />
</GroupBox>

Coordinator
Aug 31, 2012 at 10:39 AM

Very nice, I will include it. Thanks for the addition!

Coordinator
Sep 1, 2012 at 1:21 PM

I made a few improvements:

1) default values are 0d and 1d instead of 0 and 1

2) Instead of returning 1d when the value is not a bool, the converter now returns TrueResult.

Thank you very much for your contribution.