Watermark / hint text / placeholder TextBox

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

    This is a sample which demonstrates how to create a watermark textbox in WPF:

    
    
        
    
            
            
            
    
            
            
    
            
    
        
    
    
        
    
            
                
                
                
            
    
            
                
                
            
    
            
                
                    
                        
                            
                            
                        
                    
                
                
            
    
        
    
    
    

    TextInputToVisibilityConverter is defined as:

    using System;
    using System.Windows.Data;
    using System.Windows;
    
    namespace WaterMarkTextBoxDemo
    {
        public class TextInputToVisibilityConverter : IMultiValueConverter
        {
            public object Convert( object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture )
            {
                // Always test MultiValueConverter inputs for non-null
                // (to avoid crash bugs for views in the designer)
                if (values[0] is bool && values[1] is bool)
                {
                    bool hasText = !(bool)values[0];
                    bool hasFocus = (bool)values[1];
    
                    if (hasFocus || hasText)
                        return Visibility.Collapsed;
                }
    
                return Visibility.Visible;
            }
    
    
            public object[] ConvertBack( object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture )
            {
                throw new NotImplementedException();
            }
        }
    }
    

    Note: This is not my code. I found it here, but I think this is the best approach.

提交回复
热议问题