【小企】WPF实现TextBox水印效果

在日常项目中,一个TextBox需要输入用户名,我们通常的做法是先用一个TextBlock来说明,例如下面的截图:

今天将使用另外一种方式来展示,使用水印的方式。请参考下面的代码:

复制代码
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="booleanToVisibilityConverter"/>
        <Style x:Key="EntryFieldStyle" TargetType="Grid" >
            <Setter Property="HorizontalAlignment" Value="Stretch" />
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="Margin" Value="20,0" />
        </Style>
    </Window.Resources>
    <Grid Style="{StaticResource EntryFieldStyle}">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <TextBlock 
                    Text="请输入用户名" Margin="5,2"
                    Visibility="{Binding ElementName=txtWatermark, Path= Text.IsEmpty,
                    Converter={StaticResource booleanToVisibilityConverter}}"/>
            <TextBox x:Name="txtWatermark" Background="Transparent" BorderBrush="Indigo"/>
        </Grid>
    </Grid>
复制代码

运行效果截图:

我们可以把这个封装成一个UserControl,这样就可以复用了。可以下载我的项目代码,我已经把它封装成一个控件。代码下载

当然我们也可以使用其他控件实现,例如 Extended WPF Toolkit 的 WatermarkTextBox 控件。

如果有其他实现方式欢迎与我分享。感谢你的阅读。


猜你喜欢

转载自blog.csdn.net/zhuqihe02/article/details/40261355