AppThemeBinding with StaticResource in Codebehind

Jassim Al Rahma 1,521 Reputation points
2023-01-05T22:50:44.99+00:00

Hi,

How can I set the below TextColor in Codebehind?

TextColor="{AppThemeBinding Light={StaticResource FontIconLight}, Dark={StaticResource FontIconDark}}"  

Thanks,
Jassim

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,855 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,261 Reputation points Microsoft Vendor
    2023-01-06T03:00:23.457+00:00

    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 the Resources/Styles/Colors.xaml, you need to create a custom static dictionary to access merged dictionaries in App.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.

    1 person found this answer helpful.