如何实现CollectionLengthToVisibility转换器?

时间:2013-02-16 18:05:40

标签: c# windows-phone-7 xaml binding

我想实现转换器,以便某些XAML元素仅在ObservableCollection中有项目时才会显示/消失。

我引用了How to access generic property without knowing the closed generic type但无法使用它来实现我的实现。它构建和部署OK(到Windows Phone 7模拟器和设备)但不起作用。此外,Blend会抛出异常,不再呈现页面,

  

NullReferenceException:未将对象引用设置为的实例   对象

这是我到目前为止所拥有的,

// 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;
    }


}

以下是我在Blend / XAML

上引用转换器的方法
<TextBlock Visibility="{Binding QuickProfiles, ConverterParameter=CollapsedOnEmpty, Converter={StaticResource CollectionLengthToVisibility}}">Some Text</TextBlock>

1 个答案:

答案 0 :(得分:2)

我会使用Enumerable.Any()扩展方法。它适用于任何IEnumerable<T>,并避免您必须知道您正在处理什么类型的集合。由于您不知道T,因此您可以使用.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();
    }


}