【WPF】TextBox 、PasswordBox水印效果

两种方式可以实现 TextBox的水印效果

1、行为,详细请看

2、样式,下面主要介绍样式现实水印效果。

效果如下:

 

 

 

xaml完整代码

<Window x:Class="WpfApp05.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:WpfApp05"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" WindowStyle="None" Background="Transparent" AllowsTransparency="True"
        ResizeMode="NoResize" WindowStartupLocation="CenterScreen" SizeToContent="WidthAndHeight">
    <Window.Resources>
        <Style TargetType="TextBox" x:Key="UserNameTextBoxStyle">
            <Setter Property="Height" Value="35"/>
            <Setter Property="FontSize" Value="14"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TextBox">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" 
                                    BorderThickness="{TemplateBinding BorderThickness}" 
                                    Background="{TemplateBinding Background}" 
                                    SnapsToDevicePixels="True"
                                    CornerRadius="5">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="40"/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <Border BorderBrush="#DDD" BorderThickness="0,0,1,0" Margin="0,8,5,8"/>
                                <TextBlock Text="请输入用户名" Grid.Column="1" VerticalAlignment="Center" Foreground="#BBB"
                                           Name="markText" Visibility="Collapsed" FontSize="12" Margin="2,0"/>

                                <Image Source="Resources/user.png" Width="20" Height="20"/>

                                <ScrollViewer x:Name="PART_ContentHost" Focusable="false"
                                                  HorizontalScrollBarVisibility="Hidden" 
                                                  VerticalScrollBarVisibility="Hidden"
                                                  Grid.Column="1"
                                                  VerticalAlignment="Center" MinHeight="20"/>
                            </Grid>
                        </Border>

                        <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="#FF7EB4EA"/>
                            </Trigger>
                            <Trigger Property="IsKeyboardFocused" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
                            </Trigger>
                            <DataTrigger Binding="{Binding Path=Text,RelativeSource={RelativeSource Mode=Self}}" Value="">
                                <Setter Property="Visibility" TargetName="markText" Value="Visible"/>
                            </DataTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <Style TargetType="PasswordBox" x:Key="PasswordBoxStyle">
            <Setter Property="Height" Value="35"/>
            <Setter Property="FontSize" Value="14"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="PasswordBox">
                        <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" 
                                    BorderThickness="{TemplateBinding BorderThickness}" 
                                    Background="{TemplateBinding Background}" 
                                    SnapsToDevicePixels="True"
                                    CornerRadius="5">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="40"/>
                                    <ColumnDefinition/>
                                </Grid.ColumnDefinitions>
                                <Border BorderBrush="#DDD" BorderThickness="0,0,1,0" Margin="0,8,5,8"/>
                                <TextBlock Text="请输入密码" Grid.Column="1" VerticalAlignment="Center" Foreground="#BBB"
                                           Name="markText" Visibility="Collapsed" FontSize="12" Margin="2,0"/>

                                <Image Source="Resources/password.png" Width="20" Height="20"/>
                                <ScrollViewer x:Name="PART_ContentHost" Focusable="false"
                                                  HorizontalScrollBarVisibility="Hidden" 
                                                  VerticalScrollBarVisibility="Hidden"
                                                  Grid.Column="1"
                                                  VerticalAlignment="Center" MinHeight="20"/>
                            </Grid>
                        </Border>

                        <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="#FF7EB4EA"/>
                            </Trigger>
                            <Trigger Property="IsKeyboardFocused" Value="true">
                                <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
                            </Trigger>
                            <!--PasswordBox需要绑定到ViewModel才行-->
                            <DataTrigger Binding="{Binding Path=UserModel.Password}" Value="">
                                <Setter Property="Visibility" TargetName="markText" Value="Visible"/>
                            </DataTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>

    <Window.Triggers>
        <EventTrigger RoutedEvent="Window.Loaded">
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation To="0" Duration="0:0:0.5"
                                     Storyboard.TargetName="tt"
                                     Storyboard.TargetProperty="X"/>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Window.Triggers>

    <Grid Width="780" Margin="5" Background="Transparent" MouseLeftButtonDown="Grid_MouseLeftButtonDown">
        <Border Background="#F7F9FA" Margin="0,6" HorizontalAlignment="Right" Width="360" BorderThickness="0"
                CornerRadius="5">
            <Border.RenderTransform>
                <TranslateTransform X="-330" x:Name="tt"/>
            </Border.RenderTransform>
            <Grid Margin="60,0,20,20">
                <Grid.RowDefinitions>
                    <RowDefinition Height="30"></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                    <RowDefinition></RowDefinition>
                </Grid.RowDefinitions>

                <Button HorizontalAlignment="Right" Width="30" Height="30" VerticalAlignment="Top" Background="Transparent"
                        BorderBrush="Transparent" Click="btnClose_Click">
                    
                </Button>
                <StackPanel Grid.Row="1">
                    <TextBlock Text="主标题" Foreground="#333" FontSize="22"/>
                    <TextBlock Text="副标题" FontSize="12" Foreground="#888" Margin="0,10,0,0"/>
                </StackPanel>

                <!--用户名-->
                <TextBox x:Name="txtUserName" Grid.Row="3" Style="{StaticResource UserNameTextBoxStyle}"/>
                <PasswordBox x:Name="pwd" Grid.Row="4" Style="{StaticResource PasswordBoxStyle}"/>

                <CheckBox Grid.Row="5" Content="记住登录信息" VerticalAlignment="Center" FontSize="10" VerticalContentAlignment="Center"/>
                <TextBlock Grid.Row="5" HorizontalAlignment="Right" VerticalAlignment="Center">
                    <Hyperlink>忘记密码</Hyperlink>
                </TextBlock>
                <Button Content="登    录" Background="#FF104991" Foreground="White" Grid.Row="6" Height="30" Margin="0,8" BorderThickness="0" VerticalAlignment="Top"
                        Command="{Binding LoginCommand}"
                        CommandParameter="{Binding .,RelativeSource={RelativeSource AncestorType=Window}}"/>

                <TextBlock Text="Error Message" Foreground="Red" Grid.Row="7" TextWrapping="Wrap" LineHeight="23"
                           TextAlignment="Center"/>
            </Grid>
        </Border>

    </Grid>
</Window>

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
    public class UserModel : NotifyBase
    {
        private string _userName;

        public string UserName
        {
            get { return _userName; }
            set
            {
                _userName = value;
                this.NotifyChanged();
            }
        }

        private string _password = "";

        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                this.NotifyChanged();
            }
        }
    }
    public class NotifyBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyChanged([CallerMemberName] string propName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
    }
 
}

 

WPF之TextBox和PasswordBox水印效果

重要提示

 以下方法中PasswordBox 水印效果适合.net4.8 。在.net6.0 环境中会出现4个XDG006错误 ,导致再编辑环境中不能正常显示,不过可以正常编译和运行

在博客园里看到了好多关于文本框和密码框水印效果的文章,今天有空也来实现一把,最终效果图如下:

文本框的话,稍微好一点直接可以绑定它的Text属性,因为他是个依赖属性,我用了二种方式来实现水印效果:触发器和数据绑定的形式;

一、触发器方式:

复制代码
<!--触发器的形式进行水印效果-->
    <Style x:Key="TxbTrigger" TargetType="TextBox" BasedOn="{StaticResource TxbBase}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                        <Grid>
                            <ScrollViewer x:Name="PART_ContentHost" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                            <TextBlock x:Name="WaterMark" Focusable="False" Visibility="Collapsed" Text="{TemplateBinding Tag}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Opacity="0.5"/>
                        </Grid>
                    </Border>
                    <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="#FF7EB4EA"/>
                        </Trigger>
                        <Trigger Property="IsKeyboardFocused" Value="True">
                            <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
                        </Trigger>
                        <Trigger Property="Text" Value="">
                            <Setter Property="Visibility" TargetName="WaterMark" Value="Visible"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
复制代码

二、数据绑定方式

复制代码
<!--绑定和转换器的形式进行水印效果-->
    <Style x:Key="TxbBing" TargetType="TextBox" BasedOn="{StaticResource TxbBase}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                        <Grid>
                            <ScrollViewer x:Name="PART_ContentHost" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                            <TextBlock x:Name="WaterMark" Focusable="False" Visibility="{TemplateBinding Text,Converter={StaticResource TextToVisibility}}" Text="{TemplateBinding Tag}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Opacity="0.5"/>
                        </Grid>
                    </Border>
                    <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="#FF7EB4EA"/>
                        </Trigger>
                        <Trigger Property="IsKeyboardFocused" Value="True">
                            <Setter Property="BorderBrush" TargetName="border" Value="#FF569DE5"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
复制代码

 

密码框的水印效果就稍微麻烦一点了,因为这个Password它不是依赖属性,所以不能像TextBox的Text进行绑定操作;我这边是通过附加属性的形式进行实现;

代码如下:

复制代码
 /// <summary>
    /// PasswordBox添加水印辅助类
    /// </summary>
    public class PasswordBoxWaterMark : DependencyObject
    {
        public static bool GetIsMonitoring(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsMonitoringProperty);
        }

        public static void SetIsMonitoring(DependencyObject obj, bool value)
        {
            obj.SetValue(IsMonitoringProperty, value);
        }

        public static readonly DependencyProperty IsMonitoringProperty =
            DependencyProperty.RegisterAttached("IsMonitoring", typeof(bool), typeof(PasswordBoxWaterMark), new UIPropertyMetadata(false, OnIsMonitoringChanged));



        public static int GetPasswordLength(DependencyObject obj)
        {
            return (int)obj.GetValue(PasswordLengthProperty);
        }

        public static void SetPasswordLength(DependencyObject obj, int value)
        {
            obj.SetValue(PasswordLengthProperty, value);
        }

        public static readonly DependencyProperty PasswordLengthProperty =
            DependencyProperty.RegisterAttached("PasswordLength", typeof(int), typeof(PasswordBoxWaterMark), new UIPropertyMetadata(0));

        private static void OnIsMonitoringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var pb = d as PasswordBox;
            if (pb == null)
            {
                return;
            }
            if ((bool)e.NewValue)
            {
                pb.PasswordChanged += PasswordChanged;
            }
            else
            {
                pb.PasswordChanged -= PasswordChanged;
            }
        }

        private static void PasswordChanged(object sender, RoutedEventArgs e)
        {
            var pb = sender as PasswordBox;
            if (pb == null)
            {
                return;
            }
            SetPasswordLength(pb, pb.Password.Length);
        }
    }
复制代码

PasswordBox的样式如下:

复制代码
<Style TargetType="PasswordBox">
        <Setter Property="Foreground" Value="Red"/>
        <Setter Property="FontSize" Value="20"/>
        <!--光标的颜色-->
        <Setter Property="CaretBrush" Value="Green"/>
        <Setter Property="Core:PasswordBoxWaterMark.IsMonitoring" Value="true"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type PasswordBox}">
                    <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                        <Grid>
                            <ScrollViewer x:Name="PART_ContentHost" Focusable="False" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
                            <TextBlock x:Name="WaterMark" Focusable="False" Visibility="Collapsed" Text="{TemplateBinding Tag}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Opacity="0.5"/>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="Core:PasswordBoxWaterMark.PasswordLength" Value="0">
                            <Setter TargetName="WaterMark" Property="Visibility" Value="Visible"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
复制代码

源码如下:Demo.Zip

posted @ 2022-08-15 11:40  小林野夫  阅读(613)  评论(0编辑  收藏  举报
原文链接:https://www.cnblogs.com/cdaniu/