【问题标题】:How do I implement a CollectionLengthToVisibility converter?如何实现 CollectionLengthToVisibility 转换器?
【发布时间】:2013-02-01 12:48:41
【问题描述】:

我想实现一个转换器,以便某些 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>

【问题讨论】:

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


    【解决方案1】:

    我会使用Enumerable.Any() 扩展方法。它适用于任何IEnumerable&lt;T&gt;,并且避免您必须知道您正在处理什么样的集合。因为你不知道T,你可以用.Cast&lt;object&gt;()

    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();
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-24
      • 1970-01-01
      • 2016-03-19
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多