ColorPickerControl.xaml.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System;
  2. using System.Globalization;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using System.Windows.Data;
  6. using System.Windows.Media;
  7. namespace ComPDFKitDemo.AnnotControl
  8. {
  9. public partial class ColorPickerControl : UserControl
  10. {
  11. public ColorPickerControl()
  12. {
  13. InitializeComponent();
  14. colorlistbox.SelectionChanged += new SelectionChangedEventHandler(colorlistbox_SelectionChanged);
  15. }
  16. #region DependencyProperty
  17. public Color Value
  18. {
  19. get { return (Color)GetValue(ValueProperty); }
  20. set { SetValue(ValueProperty, value); }
  21. }
  22. public event RoutedEventHandler ValueChanged
  23. {
  24. add { AddHandler(ValueChangedEvent, value); }
  25. remove { RemoveHandler(ValueChangedEvent, value); }
  26. }
  27. public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(Color), typeof(ColorPickerControl));
  28. public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent("ValueChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ColorPickerControl));
  29. #endregion
  30. void colorlistbox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  31. {
  32. e.Handled = true;
  33. ColorConverter cc = new ColorConverter();
  34. Color c = new Color();
  35. c = (Color)cc.ConvertBack(colorlistbox.SelectedValue, c.GetType(), null, CultureInfo.CurrentCulture);
  36. Value = c;
  37. RoutedEventArgs args = new RoutedEventArgs(ValueChangedEvent);
  38. RaiseEvent(args);
  39. }
  40. }
  41. [ValueConversion(typeof(Color), typeof(String))]
  42. public class ColorConverter : IValueConverter
  43. {
  44. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
  45. {
  46. var color = (Color)(value as Color?);
  47. //If Alpha is 00, return Transparent
  48. if (color.A.Equals(0)) return "Transparent";
  49. return "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
  50. }
  51. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  52. {
  53. var colorString = value as string;
  54. if (String.IsNullOrWhiteSpace(colorString)) return Colors.Transparent;
  55. if (colorString.Equals("Transparent")) return Colors.Transparent;
  56. byte a = 255;
  57. byte r = (byte)(System.Convert.ToUInt32(colorString.Substring(1, 2), 16));
  58. byte g = (byte)(System.Convert.ToUInt32(colorString.Substring(3, 2), 16));
  59. byte b = (byte)(System.Convert.ToUInt32(colorString.Substring(5, 2), 16));
  60. return Color.FromArgb(a, r, g, b);
  61. }
  62. }
  63. }