其他分享
首页 > 其他分享> > WPF 实现文本框textbox文字提示

WPF 实现文本框textbox文字提示

作者:互联网

在Template中添加一个textblock用于提示文本的显示,Visibility="Collapsed"

同时添加一个触发器,当textbox的text没有内容时,textblock的Visibility="Visible",显示出来

    <Style x:Key="TextBoxPlaceHolder" TargetType="{x:Type TextBox}">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBoxBase}">
                    <Grid>
                        <Border x:Name="border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True">
                            <ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" />
                        </Border>
                        <!-- 添加一个placeholder文本 -->
                        <TextBlock IsHitTestVisible="False" Visibility="Collapsed" Text="{TemplateBinding Tag}" x:Name="placeholder" FontFamily="{StaticResource LatoThin}" FontSize="{StaticResource FontSizeLarge}" Padding="{TemplateBinding Padding}" VerticalAlignment="Center" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" Foreground="{StaticResource ForegroundVeryDarkBrush}" />
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsEnabled" Value="false">
                            <Setter Property="Opacity" TargetName="border" Value="0.56" />
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
                            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.MouseOver.Border}" />
                        </Trigger>
                        <Trigger Property="IsKeyboardFocused" Value="true">
                            <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.Focus.Border}" />
                        </Trigger>
                        <!--当TextBoxPlaceHolder的text没有值时,显示placeholder-->
                        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Text}" Value="">
                            <Setter TargetName="placeholder" Property="Visibility" Value="Visible" />
                        </DataTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

 

标签:提示,Visibility,textblock,添加,文本框,Template,WPF,textbox
来源: https://www.cnblogs.com/xuzhongjie/p/16661973.html