假设我们有一个简单的窗口:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Width="300" Height="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Margin="2,2,2,2">
<TextBlock
Text="Button 1.
It has some text.
Button shouldn't shrink less then the text size."
TextWrapping="WrapWithOverflow" />
</Button>
<Button Grid.Row="1" Content="Button 2" Margin="2,2,2,2" />
</Grid>
</Window>
所需的布局应如下所示:
在文本中:使行高与 MinHeight
成比例 (*) 等于它的 Auto
高度。换句话说,将 Height
设置为 Max(1*,Auto)
。
我假设如果 WPF 能够在设置为 Auto
时自动确定行的大小,那么应该有一种方法可以让它在按比例调整大小时遵循该大小。
我发现了一些相关的问题(1、2),但无法将那里使用的技术应用到我的案例中。
目前唯一实现的结果是
- 将
Button.MinHeight
绑定(bind)到嵌套的TextBlock.ActualHeight
- 在后面的代码中:枚举放置在第一行的所有网格的 child ,找到最大的
MinHeight
,将其设置为RowDefinition.MinHeight
。看起来很糟糕,因为按钮比文本 block 大。
可能需要与Measure & Arrange
相关的东西?还是不值得付出努力,最好手动放置 MinHeight
(本地化字符串长度差异也有一些问题)?
最佳答案
这里有一个快速简单的技巧。
复制控件(并隐藏它)并使用其测量值找到 MinHeight
:
<Grid>
<Grid x:Name="dummyControl" VerticalAlignment="Center">
<Button Grid.Row="0" Margin="2,2,2,2" Visibility="Hidden" IsHitTestVisible="False">
<TextBlock
Text="Button 1.
It has some text.
Button shouldn't shrink less then the text size."
TextWrapping="WrapWithOverflow" />
</Button>
</Grid>
<Grid>
<Grid.RowDefinitions>
<RowDefinition MinHeight="{Binding ElementName=dummyControl, Path=ActualHeight}" Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Margin="2,2,2,2">
<TextBlock
Text="Button 1.
It has some text.
Button shouldn't shrink less then the text size."
TextWrapping="WrapWithOverflow" />
</Button>
<Button Grid.Row="1" Content="Button 2" Margin="2,2,2,2" />
</Grid>
</Grid>
dummyControl
的 VerticalAlignment
应该是 Stretch
以外的任何值
关于c# - 使用比例网格大小时(*)如何自动限制行/列的最小尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51178340/