如何在 Windows Phone 8.1 RT 中将颜色代码分配为资源?

How to assign a color code as a resource in Windows Phone 8.1 RT?

我想创建一个资源文件,在这个文件中,我想分配一些颜色的值(十六进制字符串)并在代码中使用它们。当我们已经有一个 resource.resx 文件并在其上添加值时,在 WP 8.0 silverlight 上显然很容易。但是在 Windows Phone 8.1 RT 中,我不知道该怎么做。请帮助我!

P/s:为了清楚起见,以Android为例,我们可以在其中创建一个color.xml文件,然后在xml代码中使用它,比如PrimaryColor 或 SecondaryColor,这是我的目的,仅适用于 Windows Phone 8.1 RT。谢谢!

添加新的 ResourceDictionary 并在其中定义颜色:

<SolidColorBrush x:Key="MyColor">#3D3D3D"</SolidColorBrush>

然后您需要将其添加到 App.xaml 以使其可在全球范围内访问:

 <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Common/Resources.xaml"></ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

您可以在 XAML 中访问它,例如:

<Border x:Name="myBorder" Background="{StaticResource MyColor}">
</Border>

在 C# 中,您可以像这样访问:

myBorder.Background = App.Current.Resources["MyColor"] as SolidColorBrush;

创建一个 XAML 文件,ColorResource.xaml 并根据您要分配的位置和方式使用

  • 画笔
  • 颜色

ColorResource.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <SolidColorBrush x:Key="PrimaryColorBrush" Color="Transparent" />
    <Color x:Key="SecondaryColor">#FF00FF00</Color>

</ResourceDictionary>

在要使用的地方加入词典:

<Page.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/ResourceDictionaries/ColorResource.xaml"/>

您通常只会使用画笔

<Border Background="{StaticResource PrimaryColorBrush}" BorderThickness="1">

只有在极少数情况下,您才会使用实际颜色

<ColorAnimation Duration="0" Storyboard.TargetName="myStory" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="{StaticResource SecondaryColor}"/>

希望对您有所帮助