50 lines
1.2 KiB
C#
50 lines
1.2 KiB
C#
using Avalonia.Data.Converters;
|
||
using System.Collections;
|
||
using System.Globalization;
|
||
|
||
namespace Cowain.Base.Converters;
|
||
|
||
|
||
public class ListCountConverter : IValueConverter
|
||
{
|
||
public ListCountConverter()
|
||
{
|
||
}
|
||
|
||
public object? Convert(object? value, Type targetType, object? prefix, CultureInfo culture)
|
||
{
|
||
if (value == null)
|
||
return 0;
|
||
|
||
// 处理集合类型
|
||
if (value is IEnumerable collection)
|
||
{
|
||
// 优化处理实现了ICollection的集合
|
||
if (collection is ICollection collectionWithCount)
|
||
return collectionWithCount.Count;
|
||
|
||
// 否则遍历计数
|
||
int count = 0;
|
||
foreach (var item in collection)
|
||
count++;
|
||
return count;
|
||
}
|
||
|
||
// 处理字符串
|
||
if (value is string str)
|
||
return str.Length;
|
||
|
||
// 处理数组
|
||
if (value.GetType().IsArray)
|
||
return ((Array)value).Length;
|
||
|
||
// 未知类型返回1(表示单个对象)
|
||
return 1;
|
||
}
|
||
|
||
public object? ConvertBack(object? value, Type targetType, object? prefix, CultureInfo culture)
|
||
{
|
||
throw new NotSupportedException("ConvertBack is not supported.");
|
||
}
|
||
}
|