Files
WCS/Cowain.Base/Converters/ListCountConverter.cs
2026-03-02 09:08:20 +08:00

50 lines
1.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.");
}
}