c# - 使用比例网格大小时(*)如何自动限制行/列的最小尺寸?

标签 c# wpf xaml

假设我们有一个简单的窗口:

<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.&#x0a;It has some text.&#x0a;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>

Normal size

看起来不错。但是,调整大小后,上方按钮的内容会被裁剪: Small size

所需的布局应如下所示:

Desired behaviour

在文本中:使行高与 MinHeight 成比例 (*) 等于它的 Auto 高度。换句话说,将 Height 设置为 Max(1*,Auto)

我假设如果 WPF 能够在设置为 Auto 时自动确定行的大小,那么应该有一种方法可以让它在按比例调整大小时遵循该大小。

我发现了一些相关的问题(12),但无法将那里使用的技术应用到我的案例中。

目前唯一实现的结果是

  • 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.&#x0a;It has some text.&#x0a;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.&#x0a;It has some text.&#x0a;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/

相关文章:

c# - 如何读取另一个进程正在使用的文件?

c# - 如何在 asp.net mvc 2 中进行整数模型验证

c# - C# enum ToString() 是否保证返回枚举名称?

c# - 无法在 WPF 圆形按钮 (XAML) 中获取边框

wpf - 没有标题空间的WPF GroupBox

c# - 过程输出捕获非常慢

.net - 需要更换第 3 方 WinForm 控件,壁橱 WPF 等效项是什么?

wpf - 从 DataTrigger 内部更改样式

c# - 具有依赖属性的转换器

C++ 和 XAML - 来自文本框的数字输入