如何以编程方式将WPF控件的颜色设置为系统颜色,以便更新颜色方案更改?

Csu*_*enő 33 c# wpf

我怎么能在WPF的代码隐藏中做到这一点?

<Grid Background="{DynamicResource {x:Static SystemColors.DesktopBrushKey}}"/>
Run Code Online (Sandbox Code Playgroud)

Csu*_*enő 14

我刚刚找到一个丑陋的解决方案:

grid1.SetResourceReference(
    Control.BackgroundProperty,
    SystemColors.DesktopBrushKey);
Run Code Online (Sandbox Code Playgroud)

我希望有人会发布一个更好的(我想看看像grid1.Background = BackgroundBrush,因为SetResourceReference的语法是从Windows Forms向后退一步).


orc*_*cun 6

扩展方法可能有帮助:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


jt0*_*000 6

这必须已添加到WPF的更高版本,因为它最初发布是因为您的原始代码适用于我(我正在使用WPF 4.5)

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