4

我有一个 WPF 页面,上面有一些数据输入文本框,它们看起来比字体需要的大得多。什么决定了文本框的高度?有没有办法把它们压扁?

文本框根据它显示的字体大小变得越来越小(所以如果我可以帮助的话,我不想直接设置 height 属性。

这是我的意思的一个例子......

<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。

4

1 回答 1

14

我的猜测是你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"and HorizontalAlignment="Center",则文本框非常大。

和的默认水平和垂直对齐方式GridTextBoxStretch这基本上意味着元素不关心并且会采用它给出的内容。所以布局引擎询问TextBox它应该有多大并且没有得到答案,所以布局询问Grid. Grid也不关心,所以最后它会询问具有固定大小的/ PageWindow然后这个大小会沿着可视化树传播(沿途考虑任何边距和填充)。最终结果是TextBox填充了整个区域。

为了证明这一点,将对齐属性从 移动GridTextBox自身。您无法在视觉上看到差异,但如果您为 Grid 设置背景颜色,您会这样做。

<Grid Background="Red">
  <TextBox VerticalAlignment="Center" HorizontalAlignment="Center"
           Text="Sample text" FontSize="2" />
</Grid>

如果您想将文本框的边框塞满文本,您也可以Padding="0"在文本框本身上进行设置。

有关 WPF 布局系统的更多信息,请参阅本文

于 2009-02-18T09:55:43.273 回答