WPF之TextBox
1. TextBox实现⽂字垂直居中
TextBox纵向长度⽐较长但⽂字字体⽐较⼩的时候,在输⼊时就会发现⽂字不是垂直居中的。⽽使⽤中我们发现,TextBox虽然可以设置⽂字的⽔平对齐⽅式,但却没有相应的属性让我们来调节他的垂直对齐⽅式。好在TextBox继承⾃Control类,可以通过修改Template模板来改变他的属性样式(TextBlock继承⾃FrameworkElement,不可进⾏模板编辑)。borderbox
<Style x:Key="Test_TextBox" TargetType="{x:Type TextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="border" Width="Auto" Height="Auto" BorderThickness="1" BorderBrush="#FF7F9DB9">
<Grid x:Name="grid" Background="#FFFFFF">
<ScrollViewer x:Name="PART_ContentHost" VerticalAlignment="Center" HorizontalAlignment="Left"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
最后应⽤⼀下样式可以了。
PS
内容宿主是⽤来呈现 TextBox 内容的元素。TextBox 的 ControlTemplate 必须仅包含⼀个标记为内容宿主元素的元素。若要将某个元素标记为内容宿主,应为它指定特殊名称 PART_ContentHost。内容
宿主元素必须为 ScrollViewer 或 AdornerDecorator。内容宿主元素可能不会承载任何⼦元素。
2. TextBox实现回车换⾏
<TextBox Height="auto" KeyDown="TextBox_KeyDown" TextWrapping="Wrap" AcceptsReturn="True"/>