Watermark / hint text / placeholder TextBox

后端 未结 30 2990
遇见更好的自我
遇见更好的自我 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:36

    I ran into a bit of difficulty when using @john-myczek's code with a bound TextBox. As the TextBox doesn't raise a focus event when it's updated, the watermark would remain visible underneath the new text. To fix this, I simply added another event handler:

    if (d is ComboBox || d is TextBox)
    {
        control.GotKeyboardFocus += Control_GotKeyboardFocus;
        control.LostKeyboardFocus += Control_Loaded;
    
        if (d is TextBox)
            (d as TextBox).TextChanged += Control_TextChanged;
    }
    
    
    private static void Control_TextChanged(object sender, RoutedEventArgs e)
    {
        var tb = (TextBox)sender;
        if (ShouldShowWatermark(tb))
        {
            ShowWatermark(tb);
        }
        else
        {
            RemoveWatermark(tb);
        }
    }
    

提交回复
热议问题