Hello,
How can I set the below TextColor in Codebehind?
You can use SetAppThemeColor to set the text color in the code behind.
For example, I have button and need to set the text color in the code behind.
- Method 1: If you put your FontIconLight Color in the current page's
<ContentPage.Resources>
.
<ContentPage.Resources\>
<Color x:Key="FontIconLight"\>red\</Color\>
<Color x:Key="LightSecondaryColor"\>Black\</Color\>
<Color x:Key="FontIconDark"\>Teal\</Color\>
<Color x:Key="DarkSecondaryColor"\>White\</Color\>
</ContentPage.Resources\>
You can use this.Resources
get the color with following code.
MyButton.SetAppThemeColor(Button.TextColorProperty, this.Resources["FontIconLight"] as Color, this.Resources["FontIconDark"] as Color);
- Method 2: If you put your
FontIconLight
Color in theResources/Styles/Colors.xaml
, you need to create a custom static dictionary to access merged dictionaries inApp.xaml.cs
like following code.
public App()
{
InitializeComponent();
MainPage = new AppShell()
ResourceDictionary = new Dictionary\<string, ResourceDictionary\>();
foreach (var dictionary in Application.Current.Resources.MergedDictionaries)
{
string key = dictionary.Source.OriginalString.Split(';').First().Split('/').Last().Split('.').First();
ResourceDictionary.Add(key, dictionary);
}
}
public static Dictionary\<string, ResourceDictionary\> ResourceDictionary;
Then you can use App.ResourceDictionary
get the color with following code.
MyButton.SetAppThemeColor(Button.TextColorProperty, (Color)App.ResourceDictionary["Colors"]["FontIconLight"], (Color)App.ResourceDictionary["Colors"]["FontIconDark"]);
Best Regards,
Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.