天天看点

WPF开发带水印的输入框

带水印的输入框,就是在文本框没有内容的时候,显示一段浅灰色的文字,当获得焦点时,这段文字消失。

我使用了一种比较简单的实现方法:

1、创建一个自定义控件。

2、添加一个TextBox和TextBlock。TextBox是真正的输入框,而TextBlock则显示水印文字。

3、在后台代码控制TextBlock的显示与否就行。

修改自定义控件的Text属性,

public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(WatermarkTextbox), new PropertyMetadata(new PropertyChangedCallback(TextPropertyChangedCallback)));
public string Text
{
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
}
public static void TextPropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    WatermarkTextbox wt = (sender as WatermarkTextbox);
    wt._InputText.Text = ((string)e.NewValue);
}
           

完整代码下载:https://download.csdn.net/download/lweiyue/10646195

WPF

继续阅读