Replies: 3 comments 6 replies
|
And just like that I found the answer, which is of course to use the AppThemeBindingExtensions class. |
1 reply
|
In Microsoft.Maui.Controls there are two extension methods you can use: public static void SetAppTheme<T>(this BindableObject self, BindableProperty targetProperty, T light, T dark) => self.SetBinding(targetProperty, new AppThemeBinding { Light = light, Dark = dark });
public static void SetAppThemeColor(this BindableObject self, BindableProperty targetProperty, Color light, Color dark)
=> SetAppTheme(self, targetProperty, light, dark);You also can make use of: Application.Current.RequestedTheme
Application.Current.RequestedThemeChangedHere's how you may go about using these to solve your problem: // Solution 1
this.SetAppTheme(ContentPage.BackgroundColorProperty, Colors.LightGray, Colors.DarkGray);
// Solution 2
this.SetAppThemeColor(ContentPage.BackgroundColorProperty, Colors.LightGray, Colors.DarkGray);
// Solution 3
this.SetValue(ContentPage.BackgroundColorProperty, Application.Current.RequestedTheme == AppTheme.Light ? Colors.LightGray : Colors.DarkGray);
Application.Current.RequestedThemeChanged += (s, e) =>
{
this.SetValue(ContentPage.BackgroundColorProperty, Application.Current.RequestedTheme == AppTheme.Light ? Colors.LightGray : Colors.DarkGray);
}; |
5 replies
|
I revisited this issue and found a solution that exposes AppThemeBinding as a BindingBase. Once expressed as a regular binding, it can be used anywhere a binding is accepted, including inside styles. The idea is to create a temporary bindable object, apply SetAppTheme(...) to it, and then project the themed value back out via a one‑way binding: public static class AppThemeBindingBase
{
public static BindingBase Create(object? light, object? dark, Element? parent = null)
{
var b = new Button { Parent = parent ?? Application.Current };
b.SetAppTheme(Button.CommandParameterProperty, light, dark);
return BindingBase.Create(static (Button b) => b.CommandParameter, BindingMode.OneWay, source: b);
}
}Resources["MyContentPageStyle"] = new Style(typeof(ContentPage))
{
Setters =
{
new Setter
{
Property = ContentPage.BackgroundColorProperty,
Value = AppThemeBindingBase.Create(Colors.LightGray, Colors.DarkGray)
}
}
}; |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hi, I am trying to setup and use a number of styles in c# that support dark mode. All the examples I see are XAML, I want to do this in code but it appears the AppThemeBinding class is internal, although it used within the .NET Maui code base to setup styles for classes like RadioButton.
If AppThemeBinding is available in XAML, how can I access it in c#?
Thanks
John
All reactions