我有一个 WPF 页面,上面有一些数据条目文本框,它们看起来比字体需要的要大得多。什么决定了文本框的高度?有没有办法把它们压扁?
文本框根据它显示的字体大小变得越来越小(所以我不想直接设置高度属性,如果可以的话。
这是我的意思的一个例子......
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="LabelStyle" TargetType="Label">
<Setter Property="HorizontalAlignment" Value="Right"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
<Style x:Key="TextBoxStyle" TargetType="TextBox">
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
</Style>
</Page.Resources>
<StackPanel>
<WrapPanel>
<Label Style="{StaticResource LabelStyle}" Content="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"/>
<TextBox Style="{StaticResource TextBoxStyle}" Text="{Binding ActualHeight, RelativeSource={RelativeSource Self}, Mode=OneWay}"/>
</WrapPanel>
<WrapPanel>
<Label Style="{StaticResource LabelStyle}" Content="{Binding ActualHeight, RelativeSource={RelativeSource Self}}"/>
<TextBox Style="{StaticResource TextBoxStyle}" Text="{Binding ActualHeight, RelativeSource={RelativeSource Self}, Mode=OneWay}"/>
</WrapPanel>
</StackPanel>
</Page>
如果您查看大小,您会看到标签比文本框大一点。将文本框上的 VerticalAlignment 更改为 Top 使其大小相同。作为临时措施,我只是将标签上的边距设置为 -2。
最佳答案
我的猜测是您的 TextBox
的容器导致它太大。
在 Kaxaml 中尝试以下 XAML:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBox Text="Sample text" FontSize="2" />
</Grid>
</Page>
这在页面中心呈现为一个非常小的文本框。如果将容器中的
VerticalAlignment="Center"
和 HorizontalAlignment="Center"
去掉,则文本框非常大。Grid
和 TextBox
的默认水平和垂直对齐方式是 Stretch
,这基本上意味着元素不关心并且会接受它给定的内容。所以布局引擎询问 TextBox
应该有多大,但没有得到答案,所以布局询问 Grid
。 Grid
也不关心,所以最后它询问 Page
/Window
,它有一个固定的大小,然后这个大小沿着可视化树向下传播(沿途考虑任何边距和填充)。最终结果是 TextBox
填满了整个区域。为了证明这一点,将对齐属性从
Grid
移动到 TextBox
本身。您在视觉上看不到差异,但如果您为 Grid 设置背景颜色,您会这样做。<Grid Background="Red">
<TextBox VerticalAlignment="Center" HorizontalAlignment="Center"
Text="Sample text" FontSize="2" />
</Grid>
如果您想将文本框的边框紧贴文本,您还可以在文本框本身上设置
Padding="0"
。有关 WPF 布局系统的更多信息,请参阅 this article。
关于.net - WPF 文本框太大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/560416/