天天看點

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

繼續閱讀