AbstractMultiConverter.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. #nullable enable
  2. using System.Globalization;
  3. using Avalonia.Data.Converters;
  4. using CommunityToolkit.Mvvm.ComponentModel;
  5. namespace InABox.Avalonia.Converters
  6. {
  7. public abstract class AbstractMultiConverter<TIn, TOut> : ObservableObject, IMultiValueConverter
  8. {
  9. protected abstract TOut Convert(IEnumerable<TIn?>? value, object? parameter = null);
  10. protected virtual IEnumerable<TIn?>? Deconvert(TOut? value, object? parameter = null)
  11. {
  12. return default;
  13. }
  14. public object?[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
  15. {
  16. var typed = value is TOut tout ? tout : default;
  17. var result = Deconvert(typed) ?? [];
  18. return result.Select(x => x as object).ToArray();
  19. }
  20. public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture)
  21. {
  22. if (values?.Any() != true)
  23. return default(TOut);
  24. var typed = values.Select(x => x is TIn tin ? tin : default);
  25. return Convert(typed, parameter);
  26. }
  27. }
  28. }