图像以适合WPF中的网格像元大小 [英] Image to fit grid cell size in WPF
问题描述
我有一个2行2列的网格. 在0,0,我有一个TextBlock,其中的某些文本可能会由于本地化而改变;在0,0,我有一个图片.
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.
以下是示例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>
用作Image元素来源的图像大小未知.
The size of the image used as the source for the Image element is unknown.
我需要网格列#0与TextBlock文本一样宽.图像应与列一样宽,并且其高度应适当设置以保持宽高比.
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.
我尝试将图像包装在 NoSizeDecorator ,但是除非我在XAML中指定图像的绝对高度和宽度,否则图像根本不会出现,因为我需要图像具有与文本相同的宽度,所以我无法做到这一点.
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.
我该怎么办?
推荐答案
您的代码应该已经完成了您想要的工作,并添加了Image.Width
属性:
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>
在这里,我们基本上是在TextBlock.ActualWidth
中设置Image.Width
属性,以确保Image
不会变得太大.无需使用昂贵的ViewBox
控件来执行此操作.
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.
这篇关于图像以适合WPF中的网格像元大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!