I want to create a type independent Converter for counting the elements in a collection with a generic type.
public class CollectionCountConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((SomeCastingType)value).Count;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException(); // not used for oneway binding
}
}
value in this case is a Collection of any type. The problem is to find the correct casting type and cast the object. What I want to have is something like
Type t = value.GetType();
ICollection<t> c = (ICollection<t>) value;
int count = c.Count();
but this does not work. I also tried to use Object as generic type, but then I get an InvalidCastException. Is there any elegant way to do it?