iamatsundere181
iamatsundere181

Reputation: 1409

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

I want to create a resource file, in this file, I want to assign some color's values (in HEX string) and use them in code. It is clearly easy on WP 8.0 silverlight when we already have a resource.resx file and just add value on it. But in Windows Phone 8.1 RT,I don't know how to do that. Please help me!

P/s: To make it clear, take a example on Android, where we can create a color.xml file and then use it in xml code, like PrimaryColor or SecondaryColor, this is my purposes, only on Windows Phone 8.1 RT. Thanks!

Upvotes: 1

Views: 118

Answers (2)

Barnstokkr
Barnstokkr

Reputation: 3129

Create a XAML file, ColorResource.xaml and depending on where and how you want to assign you can use

  • Brush
  • Color

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>

Include the dictionary where you want to use it:

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

You'll usually only use Brushes

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

Only in some rare cases will you use the actual color

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

Hope this helps

Upvotes: 1

Muhammad Hassan
Muhammad Hassan

Reputation: 1057

Add new ResourceDictionary and within it, you can define a color:

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

Then you need to add it to App.xaml to make it accessible globally:

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

You can access it in XAML like:

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

In C# you can access like:

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

Upvotes: 1

Related Questions