Reputation: 667
I'm developing an Xamarin Forms application with a Portable Class Libraries (PCL).
Always, I like to have resources into XAML files as sorted as possible. I have seen that it isn't possible create an XAML resource file directly. A solution for me is removing the App.cs file (on Portable project) and create a Forms Xaml Page as template. I have copied the code from the old App.cs to App.xaml.cs, and then I edited the xaml file.
In the App.xaml file I have defined the color and also the style for a Label. When I bind the color into the style declaration, it fails in runtime.
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
...>
<Application.Resources>
<ResourceDictionary>
<!-- LABELS -->
<Style x:Key="labelProductReference" TargetType="Label"
BasedOn="{StaticResource labelBase}" >
<Setter Property="FontSize" Value="22" />
<Setter Property="FontAttributes" Value="Bold" />
<Setter Property="HorizontalOptions" Value="StartAndExpand" />
<Setter Property="TextColor" Value="{StaticProperty textPrimaryColor}"
</Style>
...
<!-- COLORS -->
<Color x:Key="textPrimaryColor">#FFFFFF</Color>
...
</ResourceDictionary>
</Application.Resources>
</Application>
The error says:
Xamarin.Forms.Xaml.XamlParseException: Position 45:38. StaticResource not found for key textPrimaryColor
But If I bind the color where there are the Label into the page (MainPage.xaml), it works:
<Label Text="{Binding Reference}" TextColor="{StaticResource textPrimaryColor}"
Style="{StaticResource labelProductReference}" />
How I can set the color for a some control into the xaml style resource declaration?
Upvotes: 3
Views: 3500
Reputation: 667
I have found my problem while I was writing the question.
First, we have to define the colors and then the other elements that we want to use the color.
<!-- COLORS -->
<Color x:Key="textPrimaryColor">#FFFFFF</Color>
<!-- and then, in the same resource file... -->
<!-- LABELS -->
<Style x:Key="labelProductReference" TargetType="Label"
BasedOn="{StaticResource labelBase}" >
<Setter Property="FontSize" Value="22" />
<Setter Property="FontAttributes" Value="Bold" />
<Setter Property="HorizontalOptions" Value="StartAndExpand" />
<Setter Property="TextColor" Value="{StaticProperty textPrimaryColor}"
</Style>
Upvotes: 6