在twitter-bootstrap中有这么一个功能:

WPF控件开发(1) TextBox占位符

我们如何在WPF也实现类似这种写法:

<TextBox local:placeholder="请输入筛选条件..." />

 

首先熟悉一点WPF的人都知道,placeholder在这里是一个附加属性,而这个附加属性的类型是String。

第一种实现方式


首先我们想到的可能是这样:

 1 public static string GetPlaceholder1(DependencyObject obj)
 2 {
 3     return (string)obj.GetValue(Placeholder1Property);
 4 }
 5 public static void SetPlaceholder1(DependencyObject obj, string value)
 6 {
 7     obj.SetValue(Placeholder1Property, value);
 8 }
 9 public static readonly DependencyProperty Placeholder1Property =
10     DependencyProperty.RegisterAttached("Placeholder1", typeof(string), typeof(TextBoxHelper),
11         new UIPropertyMetadata(string.Empty, new PropertyChangedCallback(OnPlaceholder1Changed)));
12 public static void OnPlaceholder1Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
13 {
14     TextBox txt = d as TextBox;
15     if (txt == null || e.NewValue.ToString().Trim().Length == 0) return;
16     RoutedEventHandler loadHandler = null;
17     loadHandler = (s1, e1) =>
18     {
19         txt.Loaded -= loadHandler;
20         if (txt.Text.Length == 0)
21         {
22             txt.Text = e.NewValue.ToString();
23             txt.FontStyle = FontStyles.Italic;
24             txt.Foreground = Brushes.Gray;
25         }
26     };
27     txt.Loaded += loadHandler;
28     txt.GotFocus += (s1, e1) =>
29     {
30         if (txt.Text == e.NewValue.ToString())
31         {
32             txt.Clear();
33             txt.FontStyle = FontStyles.Normal;
34             txt.Foreground = SystemColors.WindowTextBrush;
35         }
36     };
37     txt.LostFocus += (s1, e1) =>
38     {
39         if (txt.Text.Length == 0)
40         {
41             txt.Text = e.NewValue.ToString();
42             txt.FontStyle = FontStyles.Italic;
43             txt.Foreground = Brushes.Gray;
44         }
45     };
46 }
Placeholder1

相关文章:

  • 2018-01-06
  • 2022-12-23
  • 2022-01-08
  • 2021-06-29
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-25
  • 2021-05-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-29
  • 2021-12-13
相关资源
相似解决方案