views:

29

answers:

1

Hi,

I'm trying to do an "empty list to visibility converter" for WPF. This is an IValueConverter that takes an object ( that should be a list ) and if the list is empty (or if the passed object is null ) it should return Visibility.Collapsed; if the list is not empty it should return Visibility.Visibile;

I plan to use this for a datagrid. The plan is to make the datagrid invisible (collapsed) whenever the list given to the ItemsSource is an empty list or a null.

<my:DataGrid 
                    Name="dataGridAuxiliaryTools"
                    Style="{StaticResource DataGridStyle}"
                    CellStyle="{StaticResource DataGridCellStyle}"
                    ColumnHeaderStyle="{StaticResource DataGridColumnHeaderStyle}"
                    ItemsSource="{Binding Path=Items}"
                    IsReadOnly="False"
                    Visibility="{Binding Path=Items, 
                    Converter={StaticResource emptyListToVisibilityConverter}}"
 </my:DataGrid>

I wrote the EmptyListToVisibilityConverter as follows:

public class EmptyListToVisibilityConverter : IValueConverter
    {
    public object Convert(object value, Type targetType, object parameter,
                          CultureInfo culture)
    {
        if (value == null)
        {
            return Visibility.Collapsed;
        }
        else if (value is IList<Object>)
        {
            if ((value as IList<Object>).Count == 0)
            {
                return Visibility.Collapsed;
            }
            else
            {
                return Visibility.Visible;
            }
        }
        else
        {
            return Visibility.Visible;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter,
                              CultureInfo culture)
    {
        throw new NotImplementedException();
    }

This works well when Items is given as null but when Items is given as a List it does not work ... I think that the code bellow is not correct and cannot detect if "value" is a list or not ... Any hints ?

if (value is IList<Object>)
            {
                if ((value as IList<Object>).Count == 0)
                {
                    return Visibility.Collapsed;
                }
                else
                {
                    return Visibility.Visible;
                }

Any hints on how to do this ? Thanks a lot. MadSeb

+1  A: 

My guess is that it's because of the fact that you're using IList<Object> in the converter but your actual collection is an IList<SomethingElse>. See, IList is not covariant so you can't just convert any IList<T> to an IList<Object>. My suggestion will be to try and use IEnumerable<object> in the converter instead and use the Count() extension method to determine the number of items in the collection.

karmicpuppet