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.
Try this
<Window.Background>
<StaticResource ResourceKey="WindowBackgroundBrush" />
</Window.Background>
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
The solution is to put your resources in App.xaml instead. That way you can set the Background on your Window without any problems.