AbstractMultiConverter.cs 1.2 KB

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