Image to fit grid cell size in WPF

26,628

Your code should already do what you want, with the addition of the Image.Width property:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <TextBlock x:Name="Tb" Grid.Row="0" Grid.Column="0">Foobar</TextBlock>
    <Image Source="Foobar.jpg" Grid.Row="1" Grid.Column="0" 
        Width="{Binding ActualWidth, ElementName=Tb}" />
</Grid>

Here we are basically setting the Image.Width property from the TextBlock.ActualWidth to ensure that the Image does not grow too large. There is no need to use an expensive ViewBox control to do this.

Share:
26,628
ale
Author by

ale

Updated on July 18, 2022

Comments

  • ale
    ale almost 2 years

    I have a grid with 2 rows and 2 columns. At 0,0 I have a TextBlock with some text that can change due to localization, at 1,0 I have an Image.

    Here is the example XAML:

    <Window x:Class="WpfApplication2.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
            <TextBlock x:Name="Tb" Grid.Row="0" Grid.Column="0">Foobar</TextBlock>
            <Image Source="Foobar.jpg" Grid.Row="1" Grid.Column="0" />
        </Grid>
    </Window>
    

    The size of the image used as the source for the Image element is unknown.

    I need the grid column #0 to be as wide as the TextBlock text. The image should be as wide as the column, and its height should be set properly to keep the aspect ratio.

    I tried wrapping the image in a NoSizeDecorator but that way the image does not appear at all, unless I specify the image absolute height and width in the XAML, which I cannot do as I need the image the same width of the text.

    How can I do it?

  • Clemens
    Clemens almost 10 years
    +1, but please note that Stretch="Uniform" is the default value, so there is no need to set it explicitly.
  • Sheridan
    Sheridan almost 10 years
    Thanks @Clemens (once again)... I've updated my answer accordingly.
  • ale
    ale almost 10 years
    Thanks, I had actually already tried with the Width<-Tb.ActualWidth binding but probably had messed with some other attribute and could not get it to work.. Now it works, thanks!!