HexConverter.cs 934 B

12345678910111213141516171819202122232425262728293031323334
  1. using System;
  2. using System.Globalization;
  3. using Avalonia;
  4. using Avalonia.Data.Converters;
  5. namespace ControlCatalog.Converter;
  6. public class HexConverter : IValueConverter
  7. {
  8. public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
  9. {
  10. var str = value?.ToString();
  11. if (str == null)
  12. return AvaloniaProperty.UnsetValue;
  13. if (int.TryParse(str, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int x))
  14. return (decimal)x;
  15. return AvaloniaProperty.UnsetValue;
  16. }
  17. public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
  18. {
  19. try
  20. {
  21. if (value is decimal d)
  22. return ((int)d).ToString("X8");
  23. return AvaloniaProperty.UnsetValue;
  24. }
  25. catch
  26. {
  27. return AvaloniaProperty.UnsetValue;
  28. }
  29. }
  30. }