Home > Blockchain >  WPF: How to position a text label on an image as it changes size?
WPF: How to position a text label on an image as it changes size?

Time:07-26

I have an image inside a grid control, and when I resize the window the image changes its size very nicely, scrupulously preserving its aspect ratio (uniform stretch). If I make the window very tall, the image stays centered and (relatively) small, with whitespace above and below. So far so good.

I am trying to put a small text label in the lower left corner of the image, and I want the label to stay on top of the image, even when there is extra whitespace below. Everything I’ve tried so far positions the text relative to the bottom of the grid cell itself, not the (dynamically changing) bottom of the image.

I've tried playing with Grid's auto and *, and I've tried Canvas, but I'm stumped. What am I missing? (Note I'm fine with either a XAML or C# solution.)

<Grid>
    <Grid.RowDefinitions> <RowDefinition Height="*"/> </Grid.RowDefinitions>
    <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions>
    <Image Grid.Column="0" Grid.Row="0" Source="{Binding Path=Bitmap}"/>
    <TextBox Grid.Column="0" Grid.Row="0" 
             HorizontalAlignment="Left" HorizontalContentAlignment="Center"
             Opacity="0.85" Text="..." 
            VerticalAlignment="Bottom" VerticalContentAlignment="Center"/>
</Grid>

Wrong:

wrong

Also wrong:

also wrong

Right:

right

CodePudding user response:

You can wrap both Image and TextBox with another Grid and set HorizontalAlignment="Center" and VerticalAlignment="Center" so that this inner Grid will fit to the size of Image but not fill the outer Grid.

<Grid>
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
        <Image Source="{Binding Path=Bitmap}"/>
        <TextBox HorizontalAlignment="Left" VerticalAlignment="Bottom"
                 HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
                 Opacity="0.85" Text="..."/>
    </Grid>
</Grid>
  • Related