How do I implement the CollectionLengthToVisibility converter?

I want to implement a converter so that some XAML elements show / disappear only if ObservableCollection

there are elements in there.

I have referenced How to access a shared property without knowing the private generic type , but cannot get it to work with my implementation. It builds and deploys OK (for emulator and Windows Phone 7 device) but doesn't work. Additionally, Blend will throw an exception and will no longer render the page,

NullReferenceException: Object reference not set to instance object.

That's 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 /questions/349808/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;
    }


}

      

This is how I referenced the Blend / XAML converter

<TextBlock Visibility="{Binding QuickProfiles, ConverterParameter=CollapsedOnEmpty, Converter={StaticResource CollectionLengthToVisibility}}">Some Text</TextBlock>

      

+3


source to share


1 answer


I would use an extension method Enumerable.Any()

. It will work for anyone IEnumerable<T>

and will let you know which collection you mean. Since you don't know T

, you can simply 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();
    }


}

      

+2


source







All Articles