gpt4 book ai didi

xaml - 如何绑定(bind)样式资源字典中的颜色?

转载 作者:行者123 更新时间:2023-12-04 01:55:43 25 4
gpt4 key购买 nike

我正在使用可移植类库 (PCL) 开发 Xamarin Forms 应用程序。

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

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

<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

但是如果我将有标签的颜色绑定(bind)到页面 (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>

关于xaml - 如何绑定(bind)样式资源字典中的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com