Set color from Code-Behind using Theme palette ?

2 Answers 362 Views
General Discussions
Romain
Top achievements
Rank 2
Iron
Iron
Romain asked on 01 Mar 2023, 12:25 PM

Hi,

let's take a TextBlock as an example. What's the correct syntax to set the foreground or background color from code behind, using the resources for the Windows 11 palette for instance ?

Also if using it this way, would the color automatically switch to the correct theme variation (light to dark, dark to light) ?

Thank you for your help

2 Answers, 1 is accepted

Sort by
0
Martin Ivanov
Telerik team
answered on 02 Mar 2023, 04:18 PM

Hello Romain,

You can access a color from the Telerik theme palette using the following syntax:

this.textBlock.Foreground = new SolidColorBrush(Windows11Palette.Palette.AccentColor);

However, using this approach the color won't change automatically on color variation change. In that case, you will need to manually re-set the Foreground (or whatever) property.

If you want to support a dynamic color change when the palette value gets changed (which is what happens on color variation change), you can use the Windows11Resource MarkupExtension. 

 <TextBlock Foreground="{telerik:Windows11Resource ResourceKey=AccentBrush}"/>

If you are using the Xaml version of the Telerik and the StyleManager for theming, then you will need also to merge the following resource in App.xaml. Otherwise, the dynamic change won't work.

<Application.Resources>
	<telerik:Windows11ResourceDictionary />
</Application.Resources>

However, keep in mind that, the WPF MarkupExtensions can be used only in XAML, therefore you cannot define that in C# code.

I hope that helps.

Regards,
Martin Ivanov
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

0
Romain
Top achievements
Rank 2
Iron
Iron
answered on 02 Mar 2023, 04:27 PM

Thank you for your answer.

Is there an event triggered by some Theme related classes when the theme variation is changed ? I look in the Windows11Palette and didn't find one.

I could create my own event where I switch the variation but want to check if something similar already exists.

Thank you

Martin Ivanov
Telerik team
commented on 02 Mar 2023, 05:18 PM

No such event exist. Mostly because the palette doesn't change automatically, but the change is always triggered manually by the developer. So, you know that the color variation was changed every time you call the LoadPreset method.
Romain
Top achievements
Rank 2
Iron
Iron
commented on 02 Mar 2023, 05:19 PM

Gotcha !

Thank you for your help

Tags
General Discussions
Asked by
Romain
Top achievements
Rank 2
Iron
Iron
Answers by
Martin Ivanov
Telerik team
Romain
Top achievements
Rank 2
Iron
Iron
Share this question
or