WPF開發帶水印的輸入框
阿新 • • 發佈:2018-11-26
帶水印的輸入框,就是在文字框沒有內容的時候,顯示一段淺灰色的文字,當獲得焦點時,這段文字消失。
我使用了一種比較簡單的實現方法:
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); }