FuncConverter.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using InABox.WPF;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Data;
  9. namespace InABox.Wpf;
  10. /// <remarks>
  11. /// <b>Warning:</b> this doesn't work for nullable <typeparamref name="TIn"/>. Use the non-generic <see cref="FuncConverter"/> instead.
  12. /// </remarks>
  13. public class FuncConverter<TIn, TOut>(Func<TIn, TOut> convert, Func<TOut, TIn>? convertBack = null) : IValueConverter<TIn, TOut>
  14. {
  15. public Func<TIn, TOut> ConvertFunc { get; set; } = convert;
  16. public Func<TOut, TIn>? ConvertBackFunc { get; set; } = convertBack;
  17. public object? Convert(object? value, Type targetType, object parameter, CultureInfo culture)
  18. {
  19. if(value is TIn tIn)
  20. {
  21. return ConvertFunc(tIn);
  22. }
  23. return null;
  24. }
  25. public object? ConvertBack(object? value, Type targetType, object parameter, CultureInfo culture)
  26. {
  27. if(value is TOut tOut && ConvertBackFunc is not null)
  28. {
  29. return ConvertBackFunc.Invoke(tOut);
  30. }
  31. return null;
  32. }
  33. }
  34. public class FuncConverter(Func<object?, object?> convert, Func<object?, object?>? convertBack = null) : IValueConverter
  35. {
  36. public Func<object?, object?> ConvertFunc { get; set; } = convert;
  37. public Func<object?, object?>? ConvertBackFunc { get; set; } = convertBack;
  38. public object? Convert(object? value, Type targetType, object parameter, CultureInfo culture)
  39. {
  40. return ConvertFunc(value);
  41. }
  42. public object? ConvertBack(object? value, Type targetType, object parameter, CultureInfo culture)
  43. {
  44. if(ConvertBackFunc is not null)
  45. {
  46. return ConvertBackFunc.Invoke(value);
  47. }
  48. return null;
  49. }
  50. }