用戶名輸入框:
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"/>
如果用觸發器等等,實現起來很麻煩,做了一半做不下去了,所以這么干。
