1.自定义类

using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace EasySL.UI.Controls { public class MaskTextBox : TextBox { #region MaskText /// <summary> /// view sort style, desc arrow /// </summary> public static readonly DependencyProperty MaskTextProperty = DependencyProperty.Register("MaskText",typeof(string), typeof(MaskTextBox), new PropertyMetadata(new PropertyChangedCallback(DisplayDataPropertyCallBack))); public static void DisplayDataPropertyCallBack(object sender, DependencyPropertyChangedEventArgs args) { } public string MaskText { get { return (string)GetValue(MaskTextProperty); } set { SetValue(MaskTextProperty, value); } } #endregion public MaskTextBox() { Loaded += (sender, args) => { if (string.IsNullOrEmpty(base.Text)) { base.Text = MaskText; base.Foreground = new SolidColorBrush(Colors.Gray); } }; base.GotFocus += (sender, args) => { base.Foreground = new SolidColorBrush(Colors.Black); if (base.Text == MaskText) base.Text = string.Empty; }; base.LostFocus += (sender, args) => { if (!string.IsNullOrEmpty(base.Text)) return; base.Text = MaskText; base.Foreground = new SolidColorBrush(Colors.Gray); }; } public new string Text { get { if (base.Text == MaskText) return string.Empty; else return base.Text; } set { base.Text = value; } } } }
2.在xaml里添加引用
<local:MaskTextBox Name="userName" MaskText="用户名" Width="150" Height="30" FontSize="13"/>