Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set a WPF control's color to a system color programmatically, so that it updates on color scheme changes?

Tags:

c#

wpf

How can I do this in WPF's code-behind?

<Grid Background="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/>
like image 573
Jeno Csupor Avatar asked Mar 09 '09 23:03

Jeno Csupor


4 Answers

I just found an ugly solution:

grid1.SetResourceReference(     Control.BackgroundProperty,     SystemColors.DesktopBrushKey); 

I hope someone will post a better one (I'd like to see something like grid1.Background = BackgroundBrush, because the syntax of SetResourceReference is a step backwards from Windows Forms).

like image 70
Jeno Csupor Avatar answered Sep 20 '22 13:09

Jeno Csupor


Extension methods might help:

public static class FrameworkElementExtensions {     // usage xPanel.SetBackground(SystemColors.DesktopBrushKey);     public static void SetBackground(this Panel panel, ResourceKey key)     {         panel.SetResourceReference(Panel.BackgroundProperty, key);     }      // usage xControl.SetBackground(SystemColors.DesktopBrushKey);     public static void SetBackground(this Control control, ResourceKey key)     {         control.SetResourceReference(Control.BackgroundProperty, key);     } } 
like image 32
orcun Avatar answered Sep 19 '22 13:09

orcun


This must have been added to a later version of WPF since this was originally posted because your original code works fine for me (I'm using WPF 4.5)

<Grid Background="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/>

like image 26
jt000 Avatar answered Sep 21 '22 13:09

jt000


.NET Framework Supported in: 3.0

https://msdn.microsoft.com/en-us/library/system.windows.systemcolors.highlightbrush(v=vs.85).aspx https://msdn.microsoft.com/en_us/library/system.windows.systemcolors.highlightbrushkey(v=vs.85).aspx

this.background=SystemColors.HighlightBrush;
like image 45
Nightly Avatar answered Sep 21 '22 13:09

Nightly