【问题标题】:How can I globally set a Background Color used in XAML?如何全局设置 XAML 中使用的背景颜色?
【发布时间】:2018-10-04 14:38:41
【问题描述】:

我有这个代码:

<StackLayout Padding="20"
   HorizontalOptions="CenterAndExpand" 
   VerticalOptions="CenterAndExpand" 
   BackgroundColor="Black" >

<Grid BackgroundColor="Black" >

在许多不同的地方重复同样的事情,并且都将 BackgroundColor 指定为相同。

有没有一种方法可以让我在一个地方指定这个color,然后以某种方式绑定或引用它?比如:

<Grid BackgroundColor="{ TheBackgroundColor }" >

然后在一个文件中设置 TheBackgroundColor 并在全局范围内使用。

【问题讨论】:

  • &lt;Style TargetType="StackLayout"&gt; &lt;Setter Property="BackgroundColor" Value="#ff0000" /&gt; &lt;/Style&gt;
  • 我正在寻找能够保存用于颜色的常量的东西,而不仅仅是如何设置 StackLayout 背景颜色。

标签: xamarin xamarin.forms


【解决方案1】:

您可以在 App.xaml 中定义所有要使用的颜色,如下所示

<ResourceDictionary>
     <Color x:Key="TheBackgroundColor">#2196f3</Color>
</ResourceDictionary>

像这样在 XAML 中使用

<Grid BackgroundColor="{StaticResource TheBackgroundColor}">

在代码后面这样使用

Application.Current.Resources["TheBackgroundColor"]

如果你想设置多个值,然后定义一个样式并像上面评论中所说的那样使用它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    • 2020-12-08
    • 2013-06-19
    • 1970-01-01
    • 2010-12-11
    相关资源
    最近更新 更多