WPF文本框太大了

gim*_*mpy 4 .net wpf layout textbox stretch

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

文本框根据它显示的字体大小变得越来越大(所以如果我能帮助它,我不想直接设置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>
Run Code Online (Sandbox Code Playgroud)

如果您查看尺寸,您会看到标签比文本框略大.将文本框上的VerticalAlignment更改为Top可使其大小相同.作为一项临时措施,我只需在标签上设置一个保证金为-2.

Dre*_*kes 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>
Run Code Online (Sandbox Code Playgroud)

这将呈现为页面中心的一个非常小的文本框.如果从容器中删除VerticalAlignment="Center"HorizontalAlignment="Center",则文本框非常大.

默认的水平和垂直对齐的GridTextBoxStretch,这基本上意味着该元素不关心,并会采取什么它给了.因此布局引擎会询问TextBox它应该有多大并且没有得到答案,因此布局会询问Grid.该Grid不关心要么所以最后它要求Page/ Window,其中有一个固定的大小,然后将此大小向下传播的可视化树(采取任何边距和填充沿途考虑).最终结果是TextBox填满了整个区域.

为了证明这一点,将对齐属性从自身移动GridTextBox自身.虽然您可以为网格设置背景颜色,但您无法在视觉上看到差异.

<Grid Background="Red">
  <TextBox VerticalAlignment="Center" HorizontalAlignment="Center"
           Text="Sample text" FontSize="2" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

如果要将文本框的边框直接填充到文本上,也可以Padding="0"在文本框本身上进行设置.

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