Reputation: 35
Simply want to set Foreground
color of a TextBlock
to LightGreen
in dark mode , set to DarkGreen
in light mode. There is a theme setting in my app. I want the color adjust both system setting and app setting.
I tried this when page loaded:
var isDark = ThemeSelectorService.Theme == ElementTheme.Dark;
if(ThemeSelectorService.Theme == ElementTheme.Default)
{
isDark = Application.Current.RequestedTheme == ApplicationTheme.Dark;
}
PriceText.Foreground = new SolidColorBrush(isDark ? Colors.LightGreen : Colors.DarkGreen);
<TextBlock x:Name="PriceText" Text="This is a Text"/>
but when I change the system setting, the color will not change until reload to this page, how to make it happen?
Upvotes: 0
Views: 1490
Reputation: 35
Answer from YanGu
Step 1: add ResourceDictionary.ThemeDictionaries to ResourceDictionary
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Light">
<SolidColorBrush x:Key="PriceBrush" Color="DarkGreen"/>
</ResourceDictionary>
<ResourceDictionary x:Key="Dark">
<SolidColorBrush x:Key="PriceBrush" Color="LightGreen"/>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
Step 2: use the SolidColorBrush for your usercontrol
<TextBlock Text="This is a text" Foreground="{ThemeResource PriceBrush}"/>
This is pretty easy but cannot be found in other questions.
Upvotes: 2
Reputation: 3032
When system color changes, the page loaded method will not be called. You could use UISettings.ColorValuesChanged Event to monitor the changes of system color.
when I change the system setting, the color will not change until reload to this page
If you change the color of your app by changing the value of FrameworkElement.RequestedTheme property which can override the app-level RequestedTheme
, you need to change the value of the FrameworkElement.RequestedTheme
property to ElementTheme.Default
to let the FrameworkElement.RequestedTheme
use the Application.RequestedTheme without reloading the page.
Please check the following code to let the color adjust system setting:
public MainPage()
{
this.InitializeComponent();
……
uiSettings.ColorValuesChanged += UiSettings_ColorValuesChanged;
}
private async void UiSettings_ColorValuesChanged(UISettings sender, object args)
{
var isDark=false;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//Change the RequestedTheme of elements to ElementTheme.Default
// if you have changed some elements' RequestedTheme property
RequestedTheme = ElementTheme.Default;
ThemeSelectorService.Theme = ElementTheme.Default;
isDark = Application.Current.RequestedTheme == ApplicationTheme.Dark;
PriceText.Foreground = new SolidColorBrush(isDark ? Colors.Green : Colors.Red);
});
}
Upvotes: 1