Search code examples
c#xamlxamarinmaui.net-8.0

How can I use Windows/Android accent color in .NET Maui?


I want to use the Accent color that user have set in the system settings, as the main theme of my app. I mean the Accent Color in Windows or the Color palette in Android

I'm not sure if there's a way to use the Windows.UI.ViewManagement and something like this (code suggested by ms Copilot):

using Windows.UI.ViewManagement;
// Inside the Page Class:
var uiSettings = new UISettings();
var accentColor = uiSettings.GetColorValue(UIColorType.Accent);

Solution

  • You can use Windows/Android accent color by the following code:

            private void Button_Clicked(object sender, EventArgs e)
            {
    #if WINDOWS
                var uiSettings = new Windows.UI.ViewManagement.UISettings();
                var color = uiSettings.GetColorValue(Windows.UI.ViewManagement.UIColorType.Accent);
                var mauicolor = Color.Parse(color.ToString());
                (sender as Button).BackgroundColor = mauicolor;
    #elif ANDROID
                var value = new Android.Util.TypedValue();
                Android.App.Application.Context.ApplicationContext.Theme.ResolveAttribute(Android.Resource.Attribute.ColorAccent, value, true);
                var contexwrapper = new AndroidX.AppCompat.View.ContextThemeWrapper(Android.App.Application.Context.ApplicationContext, Android.Resource.Style.ThemeDeviceDefault);
                contexwrapper.Theme.ResolveAttribute(Android.Resource.Attribute.ColorAccent, value, true);
                var color = value.Data;
                var mauicolor = new Android.Graphics.Color(color).ToColor();
                (sender as Button).BackgroundColor = mauicolor;
    #endif
            }
    

    Note: I tested it on the windows and worked but I didn't find any where can set the system accent on my android device and simulator. So I refer to this case: Get Android system accent color (Android 10 System color accent), and convert the java code to c#.