C#、WPF 中 DatePicker 文本框内的文本垂直对齐

问题描述 投票:0回答:1

在 C#、WPF 应用程序中,TextAlignment 将 DatePicker 文本框中的文本水平居中。垂直方向,现在它是顶部对齐的。我怎样才能让它垂直居中呢? Screenshot of issue

 <DatePicker x:Name="DatePicker01" SelectedDateFormat="Long" Height="30" FontFamily="Calibri" FontSize="16" FontWeight="Regular" TabIndex="1" BorderBrush="#162D2D" Foreground="#D9D9D9" Padding="0,0,0,0" Margin="0,0,0,15">
     <DatePicker.Resources>
         <Style TargetType="{x:Type DatePickerTextBox}">
             <Setter Property="Text" Value="Select Entry Date"/>
             <Setter Property="Padding" Value="0,0,0,0"/>
             <Setter Property="Background" Value="#FF162D2D"/>
             <Setter Property="Height" Value="28"/>
             <Setter Property="TextAlignment" Value="Center"/>
         </Style>
     </DatePicker.Resources>
 </DatePicker>

我已经尝试过以下代码,但它不起作用。

<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
c# wpf
1个回答
0
投票

要将文本垂直居中,您需要覆盖 DatePickerTextBox默认控件模板,并通过执行以下操作确保内部 ScrollViewer 居中:

 <!-- Critical part: override the ControlTemplate -->
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DatePickerTextBox}">
                        <!-- Simple Grid to host the ScrollViewer -->
                        <Grid Background="{TemplateBinding Background}">
                            <ScrollViewer x:Name="PART_ContentHost"
                                          Focusable="False"
                                          HorizontalScrollBarVisibility="Hidden"
                                          VerticalScrollBarVisibility="Hidden"
                                          VerticalAlignment="Center"
                                          HorizontalAlignment="Stretch" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

我和我一起尝试过,效果很好

© www.soinside.com 2019 - 2024. All rights reserved.