Forum Xamarin.Forms

Override built-in ColorTypeConverter with custom TypeConverter?

JohannesKeinestamJohannesKeinestam SEMember
edited July 2020 in Xamarin.Forms

Hi! We have a solution where we have an project containing various constants (which are used throughout a few separate application), such as colors. As this project does not use Xamarin in any way shape or form, it cannot use the Xamarin.Forms.Color class but instead describes these colors with our custom SharedConstants.Color class.

We want to be able to reference these colors directly throughout the app, both in C# and XAML. For the former case, it seems perfectly reasonable (if a little verbose) to have an extension method Xamarin.Forms.Color ToXamarin(this SharedConstants.Color color) to solve this. However, for using our SharedConstants.Color in XAML we are drawing a bit of a blank. The naive solution would be to create a wrapper around the constants, with a static class with properties mapping between the constants as follows (which could then be referenced in XAML with x:Static):

public static class FormsColors {
    public static Xamarin.Forms.Color HighlightColor => SharedConstants.Colors.HighlightColor.ToXamarin();
    ...
}

This is not an entirely satisfactory solution due to essentially duplicating code and requiring adding a new color in two separate files each time a new color should be added.

From digging around the Xamarin.Forms source, I see that a class ColorTypeConverter is used for transforming strings in XAML to instances of Xamarin.Forms.Color. Would it be possible to create a subclass to ColorTypeConverter and export that as the go-to TypeConverter for converting values to Xamarin.Forms.Color? It seems like ColorTypeConverter is registered as the TypeConverter for Color at a few different locations:

  • In BindableProperty.cs, line 40
  • In Color.cs, line 10
  • In ColorTypeConverter.cs, line 9

Is there a way of overriding these somehow with a custom ColorTypeConverter?

Sign In or Register to comment.