Search code examples
.net-6.0.net-maui

.Net Maui: Is it possible to convert a string to a color inside a binding?


With reference to a previous question .Net maui: How to reference a color in a binding?

I have a CollectionView, bound to an ObservableCollection populated from a SQLite databaee.

I want to display each row according to a color string held in the database table

However, I only want to store the colour value as a string.

Is it possible to convert this string to a Color within the binding or call a function to do this?

So for instance:

<Label Text="{Binding Name}"
       TextColor="{Binding ConvertStringToColor(ItemColor)}" />

Where ItemColor is a string in my collection model and can be bound to.


Solution

  • There is a class named ColorTypeConverter which can be used to convert a string to the color. Such as:

    ColorTypeConverter converter = new ColorTypeConverter();
    Color color = (Color)(converter.ConvertFromInvariantString("red"));
    

    So you can use the two line codes in a binding's converter or somewhere.