Runar Ovesen Hjerpbakk

Software Philosopher

Compiled Xamarin Forms XAML - Specified cast is not valid

After releasing a new version of Golden Ratio Calculator, I decided to compile my XAML code to increase performance. I followed this guide from Xamarin and triggered compilation of all XAML in the assembly by adding the following to my App class.

using Xamarin.Forms.Xaml;

[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
namespace GoldenRatioCalculator {
  public class App : Application {
    public const string ValueColorString = "#929292";
    public static readonly Color ValueColor = new Color(146D, 146D, 146D);
    ...

The main part of the app worked as it should, but the settings page blew up:

The specified cast is not valid

The stack trace was of little assistance.

The settings page consists of just a simple TableView with a couple of cells. By commenting out parts of page until the error stopped occurring, I found the culprit:

<Label Text="{Binding Decimals}" TextColor="{x:Static l:App.ValueColorString}" />

ValueColorString is constant in the App class shown above.

Without XAML compilation this binding works fine. The string is converted to a Color and all is well in the land. With compilation turned on however, the binding fails.

I tried changing from the color string to the actual instance of the Color, ValueColor shown above, but the value of the color value became pure white in the view. Not a pretty gray as intended.

Thus, the solution became specifying the color directly in XAML:

<Label Text="{Binding Decimals}" TextColor="#929292" />

The settings page now works, even with compiled XAML.

it-works