Using Styles and Theming maui app in C#

paramjit 276 Reputation points
2022-05-19T06:46:53.05+00:00

I am developing a crossplatform app for iOS and Android using maui. The UI and Styles are written in C#.

  public static class AppStyles
    {
static Color White = Color.FromArgb("#FFFFFF");

     static Style<Label> whiteRegular20LabelStyle;

      public static Style<Label> WhiteRegular20LabelStyle => whiteRegular20LabelStyle ?? (whiteRegular20LabelStyle = new Style<Label>(
               (Label.TextColorProperty, White),
               (Label.FontFamilyProperty, "AsapRegular"),
               (Label.FontSizeProperty, 20)
               ));
}

The style is used in the UI:

new Label { HorizontalOptions=LayoutOptions.End}.Style(AppStyles.WhiteRegular20LabelStyle),

I want to theme the app. But don't know how to use SetAppThemeColor and SetAppTheme on styles and controls.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,908 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,292 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) 26,551 Reputation points Microsoft Vendor
    2022-05-26T07:37:11.077+00:00

    Hello @paramjit ,

    SetAppTheme<T> extension method that enable VisualElement objects to respond to system theme changes, we can set Label.StyleProperty like this : label.SetAppTheme<Style<Label>>(Label.StyleProperty, lightStyle, darkStyle); refer to the following code:

     public MainPage()  
     {  
            InitializeComponent();  
            var mylabel = new Label()  
        {  
        Text = "Hi! Help me and my parent Grid to Change colors according to device theme using C#",  
       ......  
        };  
    mylabel.SetAppTheme(StyleProperty, AppStyles.WhiteRegular20LabelStyle, AppStyles.RedRegular20LabelStyle);// add red style for dark mode  
    
    Content = new Grid  
    {  
        Children =  
        {  
           mylabel  
        }  
    }.Style(AppStyles.BlackRegularGridStyle);  
        Application.Current.UserAppTheme = AppTheme.Dark;// change AppTheme for testing  
    }  
    

    For more details, refer to https://learn.microsoft.com/en-us/dotnet/maui/user-interface/system-theme-changes#extension-methods
    Or set a manual binding to AppThemeBinding, see https://github.com/dotnet/maui/blob/4340ccf4f87ffae1bf146c5ffe4908e53bd72879/src/Controls/src/Core/AppThemeBinding.cs#L5

    Best Regards,
    Wenyan Zhang


    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.