soapergem
soapergem

Reputation: 9979

How can I set the background of a StackPanel to an ImageBrush defined in a style resource?

I can apply a background image to a StackPanel with this XAML code:

<StackPanel>
  <StackPanel.Background>
    <ImageBrush ImageSource="bg.png" Stretch="Uniform" AlignmentY="Bottom" />
  </StackPanel.Background>
  ...
</StackPanel>

But that's kind of a lot to type when applied to multiple StackPanels. So I'd rather define a Style (aka Static Resource?) that I can quickly apply to the individual StackPanels.

So I started writing this:

<Window.Resources>
  <ImageBrush x:Key="SpBg" ImageSource="bg.png" Stretch="Uniform" AlignmentY="Bottom" />
  <Style x:Key="StackPanelBg" TargetType="StackPanel">
    <!-- begin invalid xaml -->
    <Setter Property="Background" Value="SpBg" />
    <!-- end invalid xaml -->
  </Style>
</Window.Resources>

So that I'd be able to do this:

<StackPanel Style="{StaticResource StackPanelBg}">
  ...
</StackPanel>

Except that doesn't work; the Setter line isn't correct. How can I make this work?

Upvotes: 0

Views: 554

Answers (1)

G.Y
G.Y

Reputation: 6159

Like that:

<Window x:Class="WpfApplication12.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>

        <ImageBrush x:Key="SpBg" ImageSource="bg.png" Stretch="Uniform" AlignmentY="Bottom" />

        <Style x:Key="StackPanelBg" TargetType="StackPanel">
            <Setter Property="Background" Value="{StaticResource SpBg}" />
        </Style>

    </Window.Resources>

    <StackPanel Style="{StaticResource StackPanelBg}">

    </StackPanel>
</Window>

Upvotes: 2

Related Questions