[英]How can I set a WPF control's color to a system color programmatically, so that it updates on color scheme changes?
How can I do this in WPF's code-behind?如何在 WPF 的代码隐藏中做到这一点?
<Grid Background="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/>
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 Forms 倒退了一步)。
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}}"/>
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);
}
}
.NET Framework Supported in: 3.0 .NET 框架支持: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 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.