Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Window background color using resource

I need to use a resource to set the color of the main window in my WPF application. Since the resource declaration comes after the window declaration (I am importing a resource dictionary), I can't use a Background property in the Window object. So, I thought I would set the background this way:

<Window.Resources>
...
</Window.Resources>

<Window.Background>
    <SolidColorBrush Color="{StaticResource WindowBackgroundBrush}"  />
</Window.Background>

My syntax is a bit off, since the object won't take a brush resource for its Color property. What's the fix? Thanks for your help.

like image 834
David Veeneman Avatar asked Jan 20 '10 14:01

David Veeneman


2 Answers

this works:

<Window x:Class="Moria.Net.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        x:Name="window"
        Background="{DynamicResource WindowBrush}"
        Width="800" Height="600">
    <Window.Resources>
        <SolidColorBrush x:Key="WindowBrush" Color="LightGray"/>
    </Window.Resources>
</Window>

the main thing to note here is the x:name in the window, and the DynamicResource in the Background property

alternativly, this works as well....

  <Window.Resources>
        <SolidColorBrush x:Key="WindowBrush" Color="LightGray"/>
    </Window.Resources>
    <Window.Style>
        <Style TargetType="{x:Type Window}">
            <Setter Property="Background" Value="{StaticResource WindowBrush}"/>
        </Style>
    </Window.Style>

As a side note, if you want to use theming for you application, you should look into component resource keys

like image 33
Muad'Dib Avatar answered Oct 20 '22 12:10

Muad'Dib


Try this

<Window.Background>
    <StaticResource ResourceKey="WindowBackgroundBrush" />
</Window.Background>
like image 95
3 revs Avatar answered Oct 20 '22 13:10

3 revs