【问题标题】:How to bind colors in the style resource dictionary?如何在样式资源字典中绑定颜色?
【发布时间】:2016-04-11 15:19:27
【问题描述】:

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

始终,我希望将资源尽可能排序到 XAML 文件中。我已经看到不可能直接创建 XAML 资源文件。我的解决方案是删除 App.cs 文件(在 Portable 项目上)并创建一个 Forms Xaml Page 作为模板。我已将旧 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:位置 45:38。未找到关键 textPrimaryColor 的静态资源

但是如果我将有标签的颜色绑定到页面(MainPage.xaml)中,它可以工作:

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

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

【问题讨论】:

  • 把你的颜色放在你的风格之上,xaml 是自上而下阅读的。
  • @ChrisW。是的!一个愚蠢的错误!我瞎了,我疯了;-)
  • 我们都曾在某个时候去过那里 :)

标签: xaml xamarin visual-studio-2015 xamarin.forms portable-class-library


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-01-18
    • 2012-05-07
    • 2011-01-09
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2019-12-14
    • 1970-01-01
    相关资源
    最近更新 更多