WP7dev

Windows Phone 7 development tips

Tag Archives: ICollection

Empty List Visibility Converter

Hiding a Listbox or any item bound to a List when this List is empty (or null) is very common. You can use this simple converter to achieve this easily, what it does is casting the List to a generic ICollection, then uses ICollection.Count to check if the list is empty. Please note that this converter use is not limited to list, anything derived from ICollection can be used with it.

EmptyListVisibilityConverter.cs :


public class EmptyListVisibilityConverter : IValueConverter

{

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

    {

        if (value == null)

            return Visibility.Collapsed;

        else

        {

            ICollection list = value as ICollection;

            if (list != null)

            {

                if (list.Count == 0)

                    return Visibility.Collapsed;

                else

                    return Visibility.Visible;

            }

            else

                return Visibility.Visible;

        }

    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    {

        throw new NotImplementedException();

    }

}


And here’s a simple example of how to use it :


<ListBox x:Name=”NameChoiceListBox”

         ItemsSource=”{Binding NamesList}”

         SelectedItem=”{Binding SelectedName, Mode=TwoWay}”

         ItemTemplate=”{StaticResource DataTemplateNameChoice}”

         Visibility=”{Binding NamesList, Converter={StaticResource EmptyListVisibilityConverter}}”>


Advertisements