防止图像拉伸超出实际大小

Prevent Image from stretching beyond actual size

我有一个 Image 控件绑定到一个源。这是我想要的:

我已尝试将 MaxWidth 和 MaxHeight 绑定到父级的实际尺寸,如下所示:

<DataTemplate x:Key="ImageDataTemplate">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <TextBlock Text="{Binding Title}" Grid.Row="0"/>
        <TextBlock Text="{Binding Type}" Grid.Row="1"/>
        <Grid x:Name="ImageWrapper" Grid.Row="1" Tapped="ImageWrapper_Tapped" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="AliceBlue">
            <Image Source="{Binding Link}" MaxWidth="{Binding ActualWidth, ElementName=ImageWrapper}" MaxHeight="{Binding ElementName=ImageWrapper, Path=ActualHeight}"/>
        </Grid>
    </Grid>
</DataTemplate>

然而,我最终没有任何图像。从背景颜色可以看出,Parent Grid 占据了所有可用的 space。但是没有图像。

有没有办法实现我想要的行为?

将图像放入 Viewbox 控件并将 Viewbox 的 StretchDirection 设置为 DownOnly。 Viewbox的Stretch 属性默认值为Uniform,不需要设置。

<Viewbox StretchDirection="DownOnly">
    <Image Source="{Binding Link}" Stretch="None"/>
</Viewbox>

也许值得注意的是,在 WPF 中,您可以直接设置图像控件的 StretchDirection,因此不需要 Viewbox。

<Image Source="{Binding Link}" StretchDirection="DownOnly"/>