Watermark / hint text / placeholder TextBox

后端 未结 30 2907
遇见更好的自我
遇见更好的自我 2020-11-22 02:20

How can I put some text into a TextBox which is removed automatically when user types something in it?

30条回答
  •  没有蜡笔的小新
    2020-11-22 02:30

    If rather than having the watermark's visibility depend on the control's focus state, you want it to depend on whether the user has entered any text, you can update John Myczek's answer (from OnWatermarkChanged down) to

    static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
        var textbox = (TextBox)d;
        textbox.Loaded += UpdateWatermark;
        textbox.TextChanged += UpdateWatermark;
    }
    
    static void UpdateWatermark(object sender, RoutedEventArgs e) {
        var textbox = (TextBox)sender;
        var layer = AdornerLayer.GetAdornerLayer(textbox);
        if (layer != null) {
            if (textbox.Text == string.Empty) {
                layer.Add(new WatermarkAdorner(textbox, GetWatermark(textbox)));
            } else {
                var adorners = layer.GetAdorners(textbox);
                if (adorners == null) {
                    return;
                }
    
                foreach (var adorner in adorners) {
                    if (adorner is WatermarkAdorner) {
                        adorner.Visibility = Visibility.Hidden;
                        layer.Remove(adorner);
                    }
                }
            }
        }
    }
    

    This makes more sense if your textbox gets focus automatically when displaying the form, or when databinding to the Text property.

    Also if your watermark is always just a string, and you need the style of the watermark to match the style of the textbox, then in the Adorner do:

    contentPresenter = new ContentPresenter {
        Content = new TextBlock {
            Text = (string)watermark,
            Foreground = Control.Foreground,
            Background = Control.Background,
            FontFamily = Control.FontFamily,
            FontSize = Control.FontSize,
            ...
        },
        ...
    }
    

提交回复
热议问题