GeometryEffectConverter.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Globalization;
  5. namespace HandyControl.Expression.Media;
  6. public sealed class GeometryEffectConverter : TypeConverter
  7. {
  8. private static readonly Dictionary<string, GeometryEffect> RegisteredEffects;
  9. static GeometryEffectConverter()
  10. {
  11. var dictionary = new Dictionary<string, GeometryEffect>
  12. {
  13. {
  14. "None",
  15. GeometryEffect.DefaultGeometryEffect
  16. },
  17. {
  18. "Sketch",
  19. new SketchGeometryEffect()
  20. }
  21. };
  22. RegisteredEffects = dictionary;
  23. }
  24. public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
  25. {
  26. return typeof(string).IsAssignableFrom(sourceType);
  27. }
  28. public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
  29. {
  30. return typeof(string).IsAssignableFrom(destinationType);
  31. }
  32. public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
  33. {
  34. if (value is string key && RegisteredEffects.TryGetValue(key, out var effect))
  35. return effect.CloneCurrentValue();
  36. return null;
  37. }
  38. public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
  39. Type destinationType)
  40. {
  41. if (typeof(string).IsAssignableFrom(destinationType))
  42. {
  43. if (value is string) return value;
  44. foreach (var pair in RegisteredEffects)
  45. if (pair.Value?.Equals(value as GeometryEffect) ?? value == null)
  46. return pair.Key;
  47. }
  48. return null;
  49. }
  50. }