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



我正在开发一个带有可移植类库(PCL)的Xamarin Forms应用程序。

我总是喜欢将资源尽可能地排序到XAML文件中。我发现直接创建XAML资源文件是不可能的。对我来说,一个解决方案是删除App.cs文件(在Portable项目中)并创建一个Forms-Xaml页面作为模板。我已经将代码从旧的App.cs复制到App.xaml.cs,然后编辑了xaml文件。

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

<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:位置45:38。找不到关键字文本PrimaryColor 的StaticResource

但是,如果我将标签所在的颜色绑定到页面中(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>

最新更新