簡體   English   中英

如何以編程方式將 WPF 控件的顏色設置為系統顏色,以便在配色方案更改時更新?

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

如何在 WPF 的代碼隱藏中做到這一點?

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

我剛剛找到了一個丑陋的解決方案:

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

我希望有人會發布一個更好的(我希望看到類似 grid1.Background = BackgroundBrush 的東西,因為 SetResourceReference 的語法是從 Windows Forms 倒退了一步)。

這必須已添加到 WPF 的更高版本中,因為這是最初發布的,因為您的原始代碼對我來說很好(我使用的是 WPF 4.5)

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

擴展方法可能會有所幫助:

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM