2013-02-16 54 views
3

我想實現一個轉換器,以便某些XAML元素只有在ObservableCollection中有項時纔會出現/消失。如何實現CollectionLengthToVisibility轉換器?

我引用了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; 
    } 


} 

這裏是我引用的共混物的轉換器/ XAML

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

回答

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


}