WPF 带有watermark的文本输入框
用户名输入框:
1.没有获取焦点时, 如果输入内容为空,显示Mask文本:Please input username。如果不为空,显示文本内容。
2.获取焦点后, 如果是Mask文本,清除。如果不是,保留输入的内容。
这种例子很多,相信大家都熟悉。
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)); 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 = Brushes.Gray; } }; base.GotFocus += (sender, args) => { base.Foreground = Brushes.Black; if (base.Text == MaskText) base.Text = string.Empty; }; base.LostFocus += (sender, args) => { if (!string.IsNullOrEmpty(base.Text)) return; base.Text = MaskText; base.Foreground = Brushes.Gray; }; } public new string Text { get { if (base.Text == MaskText) return string.Empty; else return base.Text; } set { base.Text = value; } } }
调用很简单:
<local:MaskTextBox Width="200" Height="30" Margin="20,10,10,10" x:Name="tbUserName" MaskText="Please Input Username"/>
如果用触发器等等,实现起来很麻烦,做了一半做不下去了,所以这么干。