C# 如何以编程方式将 WPF 控件的颜色设置为系统颜色,以便它在配色方案更改时更新?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/628483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I set a WPF control's color to a system color programmatically, so that it updates on color scheme changes?
提问by Csupor Jen?
How can I do this in WPF's code-behind?
我怎样才能在 WPF 的代码隐藏中做到这一点?
<Grid Background="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/>
采纳答案by Csupor Jen?
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).
我希望有人会发布一个更好的(我希望看到类似 grid1.Background = BackgroundBrush,因为 SetResourceReference 的语法是从 Windows 窗体倒退一步)。
回答by orcun
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);
}
}
回答by jt000
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)
这必须已添加到 WPF 的更高版本中,因为这是最初发布的,因为您的原始代码对我来说很好用(我使用的是 WPF 4.5)
<Grid Background="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/>
<Grid Background="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/>
回答by Nightly
.NET Framework Supported in: 3.0
.NET Framework 支持:3.0
https://msdn.microsoft.com/en-us/library/system.windows.systemcolors.highlightbrush(v=vs.85).aspxhttps://msdn.microsoft.com/en_us/library/system.windows.systemcolors.highlightbrushkey(v=vs.85).aspx
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;

