防止图像拉伸超出实际大小
Prevent Image from stretching beyond actual size
我有一个 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>
然而,我最终没有任何图像。从背景颜色可以看出,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"/>
我有一个 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>
然而,我最终没有任何图像。从背景颜色可以看出,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"/>