WP7dev

Windows Phone 7 development tips

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: