如何绑定样式资源字典中的颜色?

How to bind colors in the style resource dictionary?

我正在使用便携式 Class 库 (PCL) 开发 Xamarin Forms 应用程序。

总是,我喜欢将资源尽可能分类地放入 XAML 文件中。我已经看到不可能直接创建 XAML 资源文件。我的一个解决方案是删除 App.cs 文件(在便携式项目上)并创建一个表单 Xaml 页面作为模板。我已经将代码从旧 App.cs 复制到 App.xaml.cs,然后我编辑了 xaml 文件。

在 App.xaml 文件中,我定义了标签的颜色和样式。当我将颜色绑定到样式声明时,它在运行时失败。

<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>

错误说:

Xamarin.Forms.Xaml.XamlParseException: Position 45:38. StaticResource not found for key textPrimaryColor

但是如果我将有 Label 的颜色绑定到页面中 (MainPage.xaml),它会起作用:

<Label Text="{Binding Reference}" TextColor="{StaticResource textPrimaryColor}" 
               Style="{StaticResource labelProductReference}" />

如何将某些控件的颜色设置到 xaml 样式资源声明中?

我在写题的时候发现了我的问题。

首先,我们必须定义颜色,然后是我们要使用该颜色的其他元素。

<!-- 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>