AbstractConverter.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Globalization;
  3. using System.Windows;
  4. using System.Windows.Data;
  5. using Org.BouncyCastle.X509.Extension;
  6. namespace InABox.WPF;
  7. public class UtilityConverterEventArgs : EventArgs
  8. {
  9. public object Value { get; private set; }
  10. public object Parameter { get; private set; }
  11. public UtilityConverterEventArgs(object value, object parameter)
  12. {
  13. Value = value;
  14. Parameter = parameter;
  15. }
  16. }
  17. public delegate void UtilityCoverterEvent(object sender, UtilityConverterEventArgs args);
  18. // Freezable is a way that might allow us to pass in a DataContext (ie Viewmodel)
  19. // to static resources with XAML. Not yet tested, kept for reference
  20. // The uncertain bit is the DependencyProperty "typeof(IValueConverter)" - this
  21. // might not do what we want, as I suspect it might require a concrete type?
  22. // Ref: https://thomaslevesque.com/2011/03/21/wpf-how-to-bind-to-data-when-the-datacontext-is-not-inherited/
  23. public abstract class AbstractConverter<TIn, TOut> : /*Freezable, */ IValueConverter
  24. {
  25. public event UtilityCoverterEvent? Converting;
  26. public event UtilityCoverterEvent? Deconverting;
  27. public abstract TOut Convert(TIn value);
  28. public virtual TIn? Deconvert(TOut value)
  29. {
  30. return default;
  31. }
  32. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  33. {
  34. var typed = value is TIn tin ? tin : default;
  35. Converting?.Invoke(this, new UtilityConverterEventArgs(typed, parameter));
  36. return Convert(typed);
  37. }
  38. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  39. {
  40. var typed = value is TOut tout ? tout : default;
  41. Deconverting?.Invoke(this, new UtilityConverterEventArgs(typed, parameter));
  42. return Deconvert(typed);
  43. }
  44. // #region Freezable
  45. //
  46. // protected override Freezable CreateInstanceCore()
  47. // {
  48. // return (Freezable)Activator.CreateInstance(this.GetType())!;
  49. // }
  50. //
  51. // public static readonly DependencyProperty DataContextProperty =
  52. // DependencyProperty.Register(nameof(DataContext), typeof(object), typeof(IValueConverter),
  53. // new UIPropertyMetadata(null));
  54. //
  55. // public object DataContext
  56. // {
  57. // get { return (object)GetValue(DataContextProperty); }
  58. // set { SetValue(DataContextProperty, value); }
  59. // }
  60. //
  61. // #endregion
  62. }