Thomas Montagnoni Thomas Montagnoni - 6 months ago 204
C# Question

UWP Image overflow inside button

I'm trying to stretch an image inside a Button which is inside a stackpanel and a grid but it doesn't works. On mobile size it works very well but when the app is for an Desktop it doesn't work anymore, we can see that the image overflows.

Mobile version

And what it looks like on desktop


My code:

<StackPanel x:Name="g5" Grid.Column="1" Grid.Row="1" Padding="20" Orientation="Vertical" >
<TextBlock Text="Site" FontSize="20"/>
<Button x:Name="websiteButton" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0" Background="#fc0">
<Image x:Name="websiteImage" Source="Assets/website.png" NineGrid="0" Margin="20,20,20,20"/>

Someone can tell me what is wrong and how i can stretch the image inside the button ? Btw it's a .png file.

Thanks everyone !!


Stack Panel with Vertical orientation does not impose any limits on the Children in terms of their height. It just ensures that they are stacked one on top of another. This means, that on Desktop the Button gets large width and therefore the image grows vertically to. One way to prevent this is to set MaxHeight of the Button or of the Image inside of it.

A better solution would be to use a Grid:

    <Grid x:Name="g5" Height="200" HorizontalAlignment="Stretch" Padding="20">
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        <TextBlock Text="Site" FontSize="20"/>
        <Button Grid.Row="1" x:Name="websiteButton" HorizontalAlignment="Stretch" Margin="0" Background="#fc0">
            <Image x:Name="websiteImage" Source="/Assets/Square150x150Logo.png" NineGrid="0" Margin="20,20,20,20"/>

The second row of the Grid has "*" height, which means that it will grow to fill available space. This will limit the height of the button. The default Stretch value of the image is Uniform, which will ensure the image will look good inside the button.