图像以适合 WPF 中的网格单元大小 [英] Image to fit grid cell size in WPF

查看:16
本文介绍了图像以适合 WPF 中的网格单元大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 2 行 2 列的网格.在 0,0 时,我有一个 TextBlock,其中一些文本可能会因本地化而改变,在 1,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 示例:

Here is the example 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆