WPF TextBox和PasswordBox添加水印

本文实例为大家分享TextBox和PasswordBox加水印的方法,供大家参考,具体内容如下

Textbox加水印

Textbox加水印,需要一个VisualBrush和触发器验证Text是否为空,在空的时候设置背景的Brush就可以实现水印效果。


      
        
          
            
          
        
      
      
        
      
    

PasswordBox加水印

PasswordBox加水印,需要添加判断输入非空的依赖属性,因为PasswordBox本身没有这个属性。

通过一个PasswordLength函数判断密码框的长度是不是0,如果是0则显示背景水印,否则就隐藏。

属性部分代码,CS文件

public class PasswordBoxMonitor : 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(PasswordBoxMonitor), 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(PasswordBoxMonitor), 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;
      }
    }

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

XMAL代码


      
        
      
    


效果图

WPF TextBox和PasswordBox添加水印_第1张图片

2016-09-07 新增内容

将TextBlock暴露出来,做一个可以修改水印的Textbox控件


  
    
      
        
      
    
  
  
    
  

public partial class watermarkTextBox : TextBox
  {
    public watermarkTextBox()
    {
      InitializeComponent();
    }

    private string tbText;

    public string TbText
    {
      get
      {
        return tbText;
      }

      set
      {
        tbText = value;
      }
    }
  }

调用只有一句话

复制代码 代码如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(WPF TextBox和PasswordBox添加水印)