Open Zakariathr22 opened 7 months ago
Define a Style in the Resources
section that applies theme-based brushes.
<Page
x:Class="YourNamespace.YourPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<!-- Define a Style that applies theme-based background -->
<Style x:Key="CriticalTextBoxStyle" TargetType="TextBox">
<Setter Property="Background" Value="{ThemeResource SystemFillColorCriticalBackgroundBrush}" />
<Setter Property="Foreground" Value="{ThemeResource SystemFillColorCriticalTextBrush}" />
</Style>
</Page.Resources>
<Grid>
<TextBox x:Name="myTextBox" PlaceholderText="Enter text here"/>
</Grid>
</Page>
In the code-behind, access these resources and apply them to your controls:
public sealed partial class YourPage : Page
{
public YourPage()
{
this.InitializeComponent();
// Apply the style defined in XAML to the TextBox
myTextBox.Style = (Style)this.Resources["CriticalTextBoxStyle"];
}
}
We still can't implement theme resource in C# without going through XAML, it would be easier if there was a way to use it directly from C# code.
This workaround provides a flexible and lightweight method to achieve dynamic theme-based coloring directly in C# until the feature for direct theme resource application in C# is implemented in WinUI3.
Proposal: Enable Direct Color Changes Using Theme Resources in C# for WinUI3
Summary
I propose a feature for WinUI3 that enables direct color changes using theme resources in C#. This would allow colors to dynamically adapt when the theme changes, improving the application’s aesthetics and user experience.
Rationale
Scope
Important Notes
Currently, we have the ability to change colors using static resources in both XAML and C# code. For instance:
This works well, but when it comes to using theme resources, we can only change colors in XAML. For example:
Unfortunately, directly changing colors using theme resources in C# for WinUI3 is not currently supported. This limitation becomes apparent when the app’s theme changes after launch. Using the Previous C# code, colors remain static and do not update to reflect the new theme.
Therefore, it would be highly beneficial to have a feature that allows direct color changes using theme resources in C# for WinUI3. This would ensure that the colors adapt dynamically when the theme changes, enhancing the user experience and the overall aesthetic of the application.
Open Questions
Is there a workaround that can be used to achieve this until the feature is rolled out?