防止图像拉伸超出实际尺寸

aks*_*000 0 xaml winrt-xaml windows-10 uwp

我有一个Image控制绑定到一个源.这就是我想要的:

  • 如果源图像小于包含它的网格,则它应以原始大小显示.它不应超过100%.这是设置的行为Stretch="None".
  • 如果源图像大于父网格,则应该均匀地调整其大小以适合容器.此行为可用Stretch="Uniform".

我试图将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>
Run Code Online (Sandbox Code Playgroud)

但是,我最终根本没有图像.从背景颜色可以看出,父网格占据了所有可用空间.但是没有形象.

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

Cle*_*ens 7

将图像放入Viewbox控件并将Viewbox设置StretchDirectionDownOnly.StretchViewbox 的属性具有默认值Uniform,因此您无需进行设置.

<Viewbox StretchDirection="DownOnly">
    <Image Source="{Binding Link}" Stretch="None"/>
</Viewbox>
Run Code Online (Sandbox Code Playgroud)

也许值得注意的是,在WPF中你可以直接设置StretchDirectionImage控件,因此不需要Viewbox.

<Image Source="{Binding Link}" StretchDirection="DownOnly"/>
Run Code Online (Sandbox Code Playgroud)