Reputation: 17382
How can I collect all color codes in single file, as we could do in Android & using them by referencing that file. For now I am doing this in xaml
<Entry Placeholder="Enter name" PlaceholderColor="#177245" ></Entry>
<Entry Placeholder="Enter name" PlaceholderColor="#C04000" ></Entry>
In Xamarin.Forms
I am looking something like
<Entry Placeholder="Enter name" PlaceholderColor="@color/DimGray" ></Entry>
Upvotes: 0
Views: 1185
Reputation: 9461
Create file with your colors:
using Xamarin.Forms;
public class ColorConsts
{
public Color MyColor1 { get; } = Color.Gray;
public Color MyColor2 { get; } = Color.Blue;
}
Add object to resources and bind colors:
<ContentPage.Resources>
<local:ColorConsts x:Key="colors"/>
</ContentPage.Resources>
<StackLayout>
<!-- Place new controls here -->
<Entry Placeholder="Enter name" PlaceholderColor="{Binding Source={StaticResource colors},Path=MyColor1}" ></Entry>
</StackLayout>
If you don't want to add to all pages define it in app.xaml:
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App16.App"
xmlns:local="clr-namespace:App16"
>
<Application.Resources>
<local:ColorConsts x:Key="colors"/>
</Application.Resources>
</Application>
Same approach can be used for numeric consts, localization and can parametrise everything in you xaml.
Pros of this approach is that you can make your consts class INotifyPropertyChanged and change colors at runtime.
Upvotes: 1
Reputation: 2299
In your App.xaml you can create a resource dictionary and declare the colors in there:
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyApp.App"
xmlns:local="clr-namespace:MyApp;assembly=MyApp">
<Application.Resources>
<ResourceDictionary>
<Color x:Key="ThemeColor>#177245</Color>
<Color x:Key="BackgroundColor>#C04000</Color>
</ResourceDictionary>
</Application.Resources>
</Application>
Now in your element you simply set the color property as follows:
<Entry Placeholder="Enter name" PlaceholderColor="{StaticResource ThemeColor}" />
Upvotes: 2