3

I want to implement a converter so that certain XAML elements only appear/disappear if there are items in an ObservableCollection.

I have referenced How to access generic property without knowing the closed generic type but cannot get it to work with my implementation. It build and deploys OK (to Windows Phone 7 emulator and device) but does not work. Moreover Blend throws an exception and will no longer render the page,

NullReferenceException: Object reference not set to an instance of an object.

Here is what I have so far,

// Sets the vsibility depending on whether the collection is empty or not depending if parameter is "VisibleOnEmpty" or "CollapsedOnEmpty"
public class CollectionLengthToVisibility : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        // From https://stackoverflow.com/questions/4592644/how-to-access-generic-property-without-knowing-the-closed-generic-type
        var p = value.GetType().GetProperty("Length");
        int? length = p.GetValue(value, new object[] { }) as int?;

        string s = (string)parameter;
        if ( ((length == 0) && (s == "VisibleOnEmpty")) 
            || ((length != 0) && (s == "CollapsedOnEmpty")) )
        {
            return Visibility.Visible;
        }
        else
        {
            return Visibility.Collapsed;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        return null;
    }


}

Here is how I referenced the converter on Blend/XAML

<TextBlock Visibility="{Binding QuickProfiles, ConverterParameter=CollapsedOnEmpty, Converter={StaticResource CollectionLengthToVisibility}}">Some Text</TextBlock>
Community
  • 1
  • 1
Brendan
  • 18,771
  • 17
  • 83
  • 114

1 Answers1

2

I would use the Enumerable.Any() extension method. It will work on any IEnumerable<T> and avoids you having to know what sort of collection you're dealing with. Since you don't know T you can just use .Cast<object>()

public class CollectionLengthToVisibility : System.Windows.Data.IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo cultureInfo)
    {
        var collection = value as System.Collections.IEnumerable;
        if (collection == null)
            throw new ArgumentException("value");

        if (collection.Cast<object>().Any())
               return Visibility.Visible;
        else
               return Visibility.Collapsed;    
    }

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


}
cordialgerm
  • 8,403
  • 5
  • 31
  • 47