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

3
我正在开发一个带有可移植类库(PCL)的Xamarin Forms应用程序。
通常,我喜欢将资源尽可能排序为XAML文件。我发现无法直接创建XAML资源文件。对我来说,解决方案是删除可移植项目中的App.cs文件,并创建一个Forms 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>

错误信息为: 但是,如果我将颜色绑定到页面(MainPage.xaml)中的标签所在位置,它就可以工作:
<Label Text="{Binding Reference}" TextColor="{StaticResource textPrimaryColor}" 
               Style="{StaticResource labelProductReference}" />

我如何在XAML样式资源声明中为某个控件设置颜色?

2
将颜色放在样式之上,XAML自上而下阅读。 - Chris W.
@ChrisW。是的!一个愚蠢的错误!我太盲目了,都快疯了;-) - stivex
我们都曾经有过这样的时刻 :) - Chris W.
1个回答

6

在我提问题的过程中,我已经找到了问题所在。

首先,我们需要定义颜色,然后再定义其他想要使用该颜色的元素。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接