Jamie Law
Jamie Law

Reputation: 11

How do i set the background image of a button in a WPF Application?

I cannot find the background-Image Property in the properties panel of the button, I have the images stored for each button in the root directory of my solution as Jpegs, the project is a WPF and I don't know how to set the image in the XAML or C# code. I am developing in Visual Studio 2017 Community Edition

All problems I have seen before are for different versions of Visual Studio, so I can't find the answer

*edit - i am trying to change the background image of a button at design time in the XAML editor, not create an onclick button to change a background image. So if i have this button in XAML:

<Button x:Name="keyBtn" 
        Content="Keyboard/Mouse" 
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Width="400" Height="800" FontFamily="Verdana"         
        Background="#FFB41717" 
        Margin="0,-31,0,0"/> 

Which Part should I refer to in the ".background" property?

Upvotes: 0

Views: 13194

Answers (1)

G.Y
G.Y

Reputation: 6159

It is probably easier than you think..
Try this after you add the image to your project.

<Button x:Name="keyBtn" 
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Width="400" Height="800" FontFamily="Verdana"         
        Background="#FFB41717" 
        Margin="0,-31,0,0"> 
        <Image Source="myImage.png" />
</Button>

Note that you need to remove the content since now the image is the content.

If you wish the text as well - you can try this:

<Button x:Name="keyBtn" 
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Width="400" Height="800" FontFamily="Verdana"         
        Background="#FFB41717" 
        Margin="0,-31,0,0">
        <Grid>
            <Image Source="myImage.png" Stretch="Fill" />
            <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Text="Keyboard/Mouse" />
        </Grid>
</Button>

And there is another option - which might be exactly what you are looking for:

<Button x:Name="keyBtn" 
        Content="Keyboard/Mouse"
        HorizontalAlignment="Left" VerticalAlignment="Top" 
        Width="400" Height="800" FontFamily="Verdana"         
        Margin="0,-31,0,0">
        <Button.Background>
            <ImageBrush ImageSource="myImage.png" Stretch="Fill" />
        </Button.Background>
</Button>

But in that last option - you will have to remove the Background color as it is being replaced by the image.

Upvotes: 5

Related Questions