我正在尝试构建一个表单,根据父容器可用的宽度和相同列百分比比例自动按比例缩放上下,如下图所示:
还将有其他需要缩放的内容,例如图片和按钮(不在同一网格中),从我目前阅读的资料来看,使用Viewbox是正确的方法。
然而,当我在Stretch="Uniform"的Viewbox中包装我的网格时,文本框控件会折叠到它们的最小宽度,如下所示:
如果我增加容器宽度,所有内容都会按预期缩放(好),但文本框仍然折叠到最小可能宽度(不好):
...但我不想要这种行为 - 我希望文本框元素宽度与网格列宽度相结合,而不是依赖于内容。
现在,我已经查看了各种SO问题,其中这个问题最接近我想要的: How to automatically scale font size for a group of controls?
...但它仍未真正处理文本框宽度行为(当它与Viewbox交互时),这似乎是主要问题。
我尝试了各种东西 - 不同的HorizontalAlignment="Stretch"设置等等,但迄今为止没有任何作用。以下是我的XAML:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="5" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<StackPanel.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Silver" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</StackPanel.Background>
<Viewbox Stretch="Uniform" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Content="Field A" Grid.Column="0" Grid.Row="0" />
<TextBox Grid.Column="1" Grid.Row="0" HorizontalAlignment="Stretch"></TextBox>
<Label Content="Field B" Grid.Column="2" Grid.Row="0" />
<TextBox Grid.Column="3" Grid.Row="0" HorizontalAlignment="Stretch"></TextBox>
</Grid>
</Viewbox>
<Label Content="Other Stuff"/>
</StackPanel>
<GridSplitter Grid.Column="1" HorizontalAlignment="Stretch" Height="100" Width="5"/>
<StackPanel Grid.Column="2">
<Label Content="Body"/>
</StackPanel>
</Grid>
</Window>
Viewbox
使用其排列大小和Child.DesiredSize
来计算子元素的缩放比例。因此,在Viewbox
下设置适当的固定宽度和高度到Grid
将会非常有效。 - Alex.Wei