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

后端 未结 4 933
眼角桃花
眼角桃花 2020-12-16 09:30

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


相关标签:
4条回答
  • 2020-12-16 10:14

    .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;
    
    0 讨论(0)
  • 2020-12-16 10:19

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-16 10:21

    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).

    0 讨论(0)
  • 2020-12-16 10:23

    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}}"/>

    0 讨论(0)
提交回复
热议问题