Friday 10 June 2011

WPF & Silverlight Visibility Converter

The following is a common WPF/Silverlight converter that converts either a text or boolean value into a System.Windows.Visibility value.



public class VisibilityConverter : IValueConverter
    {

        object IValueConverter.Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //test if is null
            if (value == null || value is DBNull)
            {
                throw new NullReferenceException("Visibility value contains a null value.");
            }
 
            //string type provided
            if (value.GetType() == typeof(string))
            {
                switch (value.ToString().ToLower())
                {
                    case "true":
                    case "yes":
                        return Visibility.Visible;
                    case "no":
                    case "false":
                        return Visibility.Collapsed;
                    default:
                        throw new ArgumentException(value + " is not a valid visibility value.");
                }
            }
 
            //boolean type provided
            if (value.GetType() == typeof(bool))
            {
                if ((bool)value)
                {
                    return Visibility.Visible;
                }
 
                return Visibility.Collapsed;
            }
 
            //numeric value provided
            int intValue;
            if (int.TryParse(value.ToString(), out intValue))
            {
                if (intValue == 0)
                {
                    return Visibility.Collapsed;
                }
 
                return Visibility.Visible;
            }
 
            //unknown type provided
            throw new ArgumentException("Unknown type supplied. Visibility value cannot be determined.");
        }
 
        object IValueConverter.ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }

3 comments:

  1. Can you provide the complete project to check how the values are getting passed.

    Thanks in advance!!

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. The following is an example of a list box that's visible only when the IsVisible property of the bound data context is true.

    ListBox Visibility="{Binding Path=IsVisible, Converter={StaticResource VisibilityConverter}}" ItemsSource="{Binding Path=Items}"

    As IsVisible is a boolean value and the Visibility property of the ListBox takes a type of System.Windows.Visibility the converter will convert the boolean value to what is expected by the Visibility property.

    ReplyDelete