David Rogers
David Rogers

Reputation: 4280

Border control expands to size of Grid instead of just surrounding an Image control

I wanted a <Border> around my <Image> - sounds simple enough. but I could never get it to appear. I eventually made it "Red" with "BorderThickness=20" - then it was obvious that it was going around the entire "LayoutRoot"! Something like:

<UserControl x:Class="BorderCrossing.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">

<Grid x:Name="LayoutRoot" Margin="10" Background="Black">
    <Border Canvas.ZIndex="1" Background="White" HorizontalAlignment="Center" Opacity=".5" VerticalAlignment="Top">
        <TextBlock x:Name="idTextBlock" FontSize="20" FontWeight="Bold" Foreground="Black" Text="ID Here" />
    </Border>
    <Border Canvas.ZIndex="1" Background="Blue" BorderThickness="5" BorderBrush="AntiqueWhite">
        <Image x:Name="thumbnailImage" Height="100" Width="100" Stretch="Uniform" />
    </Border>
</Grid>

In order to "fix" this, I found that adding 'HorizontalAlignment="Left" VerticalAlignment="Top"' to the <Border> placed the border around the <Image>, as desired. I also found that I could enclose the <Border> in a <Canvas> and achieve a similar result.

What is going on? Can someone explain this in a way that will prevent my "wonder" in the future?

Thanks, David

Upvotes: 0

Views: 918

Answers (1)

Filip Skakun
Filip Skakun

Reputation: 31724

The default for VerticalAlignment and HorizontalAlignment is "Stretch", so the Border stretches to the entire available space by default. It does not happen inside of a Canvas because a Canvas does not take these properties into account when performing layout of its children, so they get the minimum size based on properties like Width, Height, MinWidth and similar properties of their children. Positioning in a Canvas is done with Canvas.Top and Canvas.Left properties, while a Grid uses the ~Alignment properties as well as Margins.

Upvotes: 1

Related Questions