Image to fit grid cell size in WPF

痞子三分冷 提交于 2020-02-27 23:26:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/24698361/image-to-fit-grid-cell-size-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!