如何实现CollectionLengthToVisibility转换器

本文关键字:CollectionLengthToVisibility 转换器 实现 何实现 | 更新日期: 2023-09-27 17:59:37

我想实现一个转换器,以便某些XAML元素只有在ObservableCollection中有项时才会出现/消失。

我已经参考了如何在不知道封闭泛型类型的情况下访问泛型属性,但无法使其与我的实现一起工作。它构建并部署正常(到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>

如何实现CollectionLengthToVisibility转换器

我将使用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();
    }

}
相关文章:
  • 没有找到相关文章