How to define a color using the Color element of the Xamarin Forms within a ResourceDictionary

1

Hello, I'm following this tutorial and, from what he shows along with the Xamarin.Forms documentation, I can create a Resource dictionary as follows:

<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary 
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="App.Assets.Colors">

    <Color x:Key="TestBlue">Blue</Color>
    <Color x:Key="TestRed">Red</Color>
    <Color x:Key="TestGreen">Green</Color>

</ResourceDictionary>

And with ResourceDictionary created, I can call it on any component, including in the global application resources like this:

<?xml version="1.0" encoding="utf-8" ?>
<Application 
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="App.App">

    <Application.Resources>
        <ResourceDictionary Source="/Assets/Colors.xaml" />
    </Application.Resources>

</Application>

The problem is that when I compile the application to be able to use this Resource somewhere in the code, it brings me a described error:

The type 'Color' does not support direct content.

Can anyone help me? I have already done this in Windows Presentation Forms and I would like to be able to better flex control variables and extend styles in a simple and dynamic way but have a good time that I do not search and do not think how to do ...

    
asked by anonymous 19.11.2018 / 21:44

1 answer

-1

The ResourceDictionary is for you to create shared resources like you said, but in this case you are trying to inform an xml file to specify the colors. The correct use would be as below.

Place the code below in App.xaml

<Application.Resources>
   <ResourceDictionary MergedWith="light:LightThemeResources">
      <!-- Cores compartilhadas -->
      <Color x:Key="BackgroundColor">#F4F6FA</Color>
      <Color x:Key="TextColor">#722881</Color>

      <!-- FONT SIZE -->

      <OnPlatform
          x:Key="MidMediumSize"
          x:TypeArguments="x:Double"
          iOS="12"
          Android="14"
          WinPhone="14"/>
   </ResourceDictionary>
</Application.Resources>

In your xaml pages you can use the resources as follows:

<Label Text="{Binding Name}" FontSize="{StaticResource MidMediumSize}" FontAttributes = "Bold" TextColor = "{StaticResource TextColor}" />
    
19.12.2018 / 14:02