水印文本框

  先看下效果:

  流程:

  1.新建WatermarkTextBox类,继承自TextBox。添加依赖项属性Watermark(水印)、WatermarkForeground(水印前景色)。

 1     public class WatermarkTextBox : TextBox
 2     {
 3         #region DependencyProperties
 4         public string Watermark
 5         {
 6             get { return (string)GetValue(WatermarkProperty); }
 7             set { SetValue(WatermarkProperty, value); }
 8         }
 9 
10         // Using a DependencyProperty as the backing store for Watermark.  This enables animation, styling, binding, etc...
11         public static readonly DependencyProperty WatermarkProperty =
12             DependencyProperty.Register("Watermark", typeof(string), typeof(WatermarkTextBox), new PropertyMetadata(default(string)));
13 
14         public Brush WatermarkForeground
15         {
16             get { return (Brush)GetValue(WatermarkForegroundProperty); }
17             set { SetValue(WatermarkForegroundProperty, value); }
18         }
19 
20         // Using a DependencyProperty as the backing store for WatermarkForeground.  This enables animation, styling, binding, etc...
21         public static readonly DependencyProperty WatermarkForegroundProperty =
22             DependencyProperty.Register("WatermarkForeground", typeof(Brush), typeof(WatermarkTextBox), new PropertyMetadata(new SolidColorBrush(Colors.Gray)));
23 
24         #endregion
25 
26         static WatermarkTextBox()
27         {
28             DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkTextBox), new FrameworkPropertyMetadata(typeof(WatermarkTextBox)));
29         }
30     }

  2.编写WatermarkTextBox样式。

 1             

  3.界面引用。

1         "Center" VerticalAlignment="Center" Orientation="Horizontal">
2             "txt"
3                                     Width="200" Height="28"
4                                     Style="{StaticResource WatermarkTextBoxStyle}"
5                                     Watermark="请输入..." />
6             

 

 

你可能感兴趣的:(水印文本框)