Image to fit grid cell size in WPF
grid, image, wpf, xaml
Solution
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.
Problem
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?