XSDVisualizer/XSDVisualiser.Desktop/Converters/CollectionHasItemsConverter.cs

37 lines
1.2 KiB
C#

using System.Collections;
using System.Globalization;
using Avalonia.Data.Converters;
namespace XSDVisualiser.Desktop.Converters;
/// <summary>
/// Returns true if the bound value is a collection with at least one item. Supports IEnumerable and ICollection.
/// Optional parameter "Invert" to invert the boolean result.
/// </summary>
public sealed class CollectionHasItemsConverter : IValueConverter
{
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
var hasItems = false;
switch (value)
{
case ICollection coll:
hasItems = coll.Count > 0;
break;
case IEnumerable enumerable:
{
var enumerator = enumerable.GetEnumerator();
hasItems = enumerator.MoveNext();
break;
}
}
var invert = parameter is string s && s.Equals("Invert", StringComparison.OrdinalIgnoreCase);
return invert ? !hasItems : hasItems;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}