OxyColorConverter.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // --------------------------------------------------------------------------------------------------------------------
  2. // <copyright file="OxyColorConverter.cs" company="OxyPlot">
  3. // Copyright (c) 2014 OxyPlot contributors
  4. // </copyright>
  5. // <summary>
  6. // Converts between <see cref="OxyColor" /> and <see cref="Color" />.
  7. // </summary>
  8. // --------------------------------------------------------------------------------------------------------------------
  9. namespace OxyPlot.Avalonia.Converters
  10. {
  11. using global::Avalonia.Data.Converters;
  12. using global::Avalonia.Media;
  13. using System;
  14. using System.Globalization;
  15. /// <summary>
  16. /// Converts between <see cref="OxyColor" /> and <see cref="Color" />.
  17. /// </summary>
  18. public class OxyColorConverter : IValueConverter
  19. {
  20. /// <summary>
  21. /// Converts a value.
  22. /// </summary>
  23. /// <param name="value">The value produced by the binding source.</param>
  24. /// <param name="targetType">The type of the binding target property.</param>
  25. /// <param name="parameter">The converter parameter to use.</param>
  26. /// <param name="culture">The culture to use in the converter.</param>
  27. /// <returns>A converted value. If the method returns <c>null</c>, the valid <c>null</c> value is used.</returns>
  28. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  29. {
  30. if (value is OxyColor color)
  31. {
  32. if (targetType == typeof(Color))
  33. {
  34. return color.ToColor();
  35. }
  36. if (targetType == typeof(IBrush))
  37. {
  38. return color.ToBrush();
  39. }
  40. }
  41. return null;
  42. }
  43. /// <summary>
  44. /// Converts a value.
  45. /// </summary>
  46. /// <param name="value">The value that is produced by the binding target.</param>
  47. /// <param name="targetType">The type to convert to.</param>
  48. /// <param name="parameter">The converter parameter to use.</param>
  49. /// <param name="culture">The culture to use in the converter.</param>
  50. /// <returns>A converted value. If the method returns <c>null</c>, the valid <c>null</c> value is used.</returns>
  51. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  52. {
  53. if (targetType == typeof(OxyColor))
  54. {
  55. if (value is Color color)
  56. {
  57. return OxyColor.FromArgb(color.A, color.R, color.G, color.B);
  58. }
  59. if (value is SolidColorBrush brush)
  60. {
  61. return OxyColor.FromArgb(brush.Color.A, brush.Color.R, brush.Color.G, brush.Color.B);
  62. }
  63. }
  64. return null;
  65. }
  66. }
  67. }