AbstractConverter.cs 2.5 KB

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