using System; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; namespace ComPDFKitDemo.AnnotControl { public partial class ColorPickerControl : UserControl { public ColorPickerControl() { InitializeComponent(); colorlistbox.SelectionChanged += new SelectionChangedEventHandler(colorlistbox_SelectionChanged); } #region DependencyProperty public Color Value { get { return (Color)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public event RoutedEventHandler ValueChanged { add { AddHandler(ValueChangedEvent, value); } remove { RemoveHandler(ValueChangedEvent, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(Color), typeof(ColorPickerControl)); public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent("ValueChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ColorPickerControl)); #endregion void colorlistbox_SelectionChanged(object sender, SelectionChangedEventArgs e) { e.Handled = true; ColorConverter cc = new ColorConverter(); Color c = new Color(); c = (Color)cc.ConvertBack(colorlistbox.SelectedValue, c.GetType(), null, CultureInfo.CurrentCulture); Value = c; RoutedEventArgs args = new RoutedEventArgs(ValueChangedEvent); RaiseEvent(args); } } [ValueConversion(typeof(Color), typeof(String))] public class ColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var color = (Color)(value as Color?); //If Alpha is 00, return Transparent if (color.A.Equals(0)) return "Transparent"; return "#" + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2"); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var colorString = value as string; if (String.IsNullOrWhiteSpace(colorString)) return Colors.Transparent; if (colorString.Equals("Transparent")) return Colors.Transparent; byte a = 255; byte r = (byte)(System.Convert.ToUInt32(colorString.Substring(1, 2), 16)); byte g = (byte)(System.Convert.ToUInt32(colorString.Substring(3, 2), 16)); byte b = (byte)(System.Convert.ToUInt32(colorString.Substring(5, 2), 16)); return Color.FromArgb(a, r, g, b); } } }