Change BooleanToVisibilityConverter

Jan 12, 2011 at 12:35 PM

Hi. As (higher-level) improvements for CM are discussed these days, I am encouraged to suggest a minor change that might come in handy for many developers. The BooleanToVisibilityConverter is very useful and meanwhile obligatory for building an improved UI. But very often I do need to invert that converter (means "False = Visible") or have something like "Null = Collapsed". As this could be implemented easily in the existing CM-Converter, I suggest to change the BooleanToVisibilityConverter to a more general VisibilityConverter like the following (used by Nikhil Khotari in at least in his famous BookClub):

 

    public sealed class VisibilityConverter : IValueConverter
    {

        public bool Inverse { get; set; }

        #region Implementation of IValueConverter
        object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType != typeof (Visibility))
                throw new ArgumentOutOfRangeException("targetType", "VisibilityConverter can only convert to Visibility");

            Visibility visibility = Visibility.Visible;

            if (value == null)
                visibility = Visibility.Collapsed;

            if (value is bool)
                visibility = (bool) value ? Visibility.Visible : Visibility.Collapsed;

            if (value is string)
                visibility = String.IsNullOrEmpty((string) value) ? Visibility.Collapsed : Visibility.Visible;

            if (Inverse)
                visibility = (visibility == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible;

            return visibility;
        }

        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is Visibility))
                throw new ArgumentOutOfRangeException("value", "VisibilityConverter can only convert from Visibility");

            if (targetType == typeof (bool))
                return ((Visibility) value == Visibility.Visible) ? true : false;

            throw new ArgumentOutOfRangeException("targetType", "VisibilityConverter can only convert to Boolean");
        }
        #endregion
    }