Sandepku Sandepku - 12 days ago 8
C# Question

WPF color picker - Add new custom color

I'm trying to add new a new custom color into the available colors of WPF color picker.

Code behind

this.colorPicker1.AvailableColors.Add(new ColorItem(Color.FromArgb(255, 153, 153, 187), "Custom"));


XAML

<exceedToolkit:ColorPicker Name="colorPicker1" DisplayColorAndName="True"/>


enter image description here

The problem is when I select this custom color, the textbox displays the hexadecimal value instead of the color's name ("Custom"),
is there a way for me to fix this?

Answer

As I mentioned in my comment above:

According to the Source Code the name isn't determined by the entries in AvailableColors but the extension method ColorUtilities.GetColorName. Maybe it will work if you add your color to ColorUtilities.KnownColors too.

A (dirty) workaround until the developers fix this would be to ignore that the ColorUtilities class is private:

public static class ColorItemExtension
{
    public static bool Register(this ColorItem colorItem)
    {
        if (colorItem.Color == null) return false;

        Assembly assembly = typeof(ColorPicker).Assembly;
        Type colorUtilityType = assembly.GetType("Xceed.Wpf.Toolkit.Core.Utilities.ColorUtilities");
        if (colorUtilityType == null) return false;

        FieldInfo fieldInfo = colorUtilityType.GetField("KnownColors");
        if (fieldInfo == null) return false;

        Dictionary<string, Color> knownColors = fieldInfo.GetValue(null) as Dictionary<string, Color>;
        if (knownColors == null) return false;
        if (knownColors.ContainsKey(colorItem.Name)) return false;

        knownColors.Add(colorItem.Name, (Color) colorItem.Color);
        return true;
    }
}

Can be used like this:

var colorItem = new ColorItem(Color.FromRgb(1, 2, 3), "Almost black");
colorItem.Register();
colorPicker1.AvailableColors.Add(colorItem);

If this is important to you, you might want to consider bringing this issue to the developers attention here