Blog
Xamarin forms: Separate resource dictionary for custom theme

Xamarin forms allows to create a separate resource dictionary file for custom theme rather than adding styles directly in App.xaml

What are the benefits?
- Code separation, Separate style code and design code rather than adding everything in one file, It’s like separating html and css code.
- Multiple theme resources, Just create multiple theme resource files for one project and apply specific theme file(s) on demand.
Quick start
- Create a separate resource dictionary
- Apply theme file(s)
- Overriding styles
Create separate resource dictionary
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CustomThemeDemo.CustomTheme">
<Color x:Key="MyCustomBackGroundColor">#DF5607</Color>
<Color x:Key="MyCustomTextColor">#484848</Color>
</ResourceDictionary>
Change the build action of CustomTheme.xaml to Embedded resource
We can add any desired styles that we want to apply in the project. Here we took an example of colors.
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CustomThemeDemo
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyCustomTheme: ResourceDictionary
{
public MyCustomTheme()
{
InitializeComponent();
}
}
}
No need to add any style specific code in .cs file
Apply theme file(s)
<Application.Resources>
<Color x:Key="PrimaryBackGroundColor">#B3B6B7</Color>
<Color x:Key="PrimaryTextColor">#707B7C</Color>
<ResourceDictionary MergedWith="local:MyCustomTheme" />
</Application.Resources>
Overriding styles
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CustomThemeDemo.CustomTheme">
<Color x:Key="PrimaryBackGroundColor">#DF5607</Color>
<Color x:Key="PrimaryTextColor">#484848</Color>
</ResourceDictionary>
It works same as CSS, This will simply override styles written in App.xaml
Conclusion
We can create as many resource files as we want to apply, We just need to create and add the file(s) in app.xaml
I hope you enjoyed this blog and it will add some value in your technical knowledge, enjoy coding..!! Thank you..!!