图像以适应 WPF 中的网格单元格大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24698361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Image to fit grid cell size in WPF
提问by ale
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.
我有一个 2 行 2 列的网格。在 0,0 我有一个 TextBlock,其中一些文本可能因本地化而改变,在 1,0 我有一个图像。
Here is the example XAML:
这是示例 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.
用作 Image 元素源的图像的大小未知。
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.
我需要网格列 #0 与 TextBlock 文本一样宽。图像应与列一样宽,其高度应适当设置以保持纵横比。
I tried wrapping the image in a NoSizeDecoratorbut 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.
我尝试将图像包装在NoSizeDecorator 中,但这样图像根本不会出现,除非我在 XAML 中指定图像的绝对高度和宽度,我不能这样做,因为我需要与文本宽度相同的图像。
How can I do it?
我该怎么做?
回答by Sheridan
Your code shouldalready do what you want, with the addition of the Image.Width
property:
您的代码应该已经完成了您想要的操作,并添加了以下Image.Width
属性:
<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.
这里我们基本上是Image.Width
从设置属性TextBlock.ActualWidth
以确保Image
不会变得太大。无需使用昂贵的ViewBox
控件来执行此操作。