karn
karn

Reputation: 51

wpf button background image

I have a wpf page with 5 button. All the 5 buttons must be of same size and all must have the same background image. How to do this?

Regards, Karn

Upvotes: 3

Views: 5710

Answers (1)

Ian Griffiths
Ian Griffiths

Reputation: 14567

Use a Style. This will automatically apply to all buttons in the Window:

<Window.Resources>
    <Style TargetType="Button">
        <Setter Property="Width" Value="100" />
        <Setter Property="Height" Value="100" />
        <Setter Property="Background">
            <Setter.Value>
                <ImageBrush ImageSource="ButtonBg.png" />
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

This sets the default Width, Height, and Background for all buttons. It assumes you have a bitmap called ButtonBg.png compiled into your project - that's the background image.

If you only want to apply this style only to certain buttons, you'd modify the first line thus:

<Style x:Key="imgBtnStyle" TargetType="Button">

And then the buttons that you want to apply this style to would need to reference that style:

<Button Style="{StaticResource imgBtnStyle}" ... />

Note that when you drag an image onto the design surface in Visual Studio 2010, it sets the Width and Height for you. This will override the style. You need to remove the Width and Height from the button elements themselves to enable the style to control those properties.

Upvotes: 7

Related Questions