tags:

views:

4421

answers:

2

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

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

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

csuporj
I don't think this is ugly. Looks pretty normal if you want to do it in code behind.
Sergey Aldoukhov
+1  A: 

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