Watermark / hint text / placeholder TextBox

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

    This technique uses the Background property to show / hide placeholder textbox.
    Placeholder is shown event when Textbox has the focus

    How it works:

    • When empty, TextBox background set to Transparent to show PlaceHolder text.
    • When not empty background set to White to cover up PlaceHolder text.

    Here is basic example. For my own purposes I turned this into a UserControl.

    
        
            
    
            
    
            
    
        
    
        
            
        
        
        
            
                
            
        
    
    

    Here is the ValueConverter to detect non-empty strings in the DataTrigger.

    public class NotEmptyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var s = value as string;
            return string.IsNullOrEmpty(s);
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
    

提交回复
热议问题