• WPF TextBox实现placeholder


    WPF里TextBox没有placeholder,需要自己实现,本篇博客介绍WPF TextBox实现placeholder,效果如下:

    在这里插入图片描述
    实现技巧是在 TextBox 控件的 Style 中使用触发器(Triggers)来显示和隐藏placeholder文本。xmal代码如下:

    <Window x:Class="WpfApp_TextBox.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp_TextBox"
            mc:Ignorable="d"
            Title="MainWindow" Height="461" Width="837">
        <Grid>
            <Canvas>
            
            <TextBox x:Name="userName" Width="240" Height="36" FontSize="16" Canvas.Left="20" Canvas.Top="20">
                <TextBox.Style>
                    <Style TargetType="TextBox">
                        "Template">
                            
                                "TextBox">
                                    
                                        x:Name="textSource" Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}}" Background="Transparent" Padding="5"/>
                                        "False" Text="Enter text here..." Foreground="Gray" Padding="5">