栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

WPF TextBox和PasswordBox添加水印

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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代码


      
 
   
   
   
   
   
     

  
    
      
      
 
      
    
  
  
    
      
    
    
      
    
  

     
   
 
      
    


效果图

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;
      }
    }
  }

调用只有一句话

复制代码 代码如下:

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/123932.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号