Watermark / hint text / placeholder TextBox

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

    My solution is quite simple.

    In my login window. the xaml is like this.

     
            
            
                
                
                
                
                
            
        
    

    the code is like this.

    private void userNameWatermarked_GotFocus(object sender, RoutedEventArgs e)
        {
            userNameWatermarked.Visibility = System.Windows.Visibility.Collapsed;
            userName.Visibility = System.Windows.Visibility.Visible;
            userName.Focus();
        }
    
        private void userName_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.userName.Text))
            {
                userName.Visibility = System.Windows.Visibility.Collapsed;
                userNameWatermarked.Visibility = System.Windows.Visibility.Visible;
            }
        }
    
        private void passwordWatermarked_GotFocus(object sender, RoutedEventArgs e)
        {
            passwordWatermarked.Visibility = System.Windows.Visibility.Collapsed;
            password.Visibility = System.Windows.Visibility.Visible;
            password.Focus();
        }
    
        private void password_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.password.Password))
            {
                password.Visibility = System.Windows.Visibility.Collapsed;
                passwordWatermarked.Visibility = System.Windows.Visibility.Visible;
            }
        }
    

    Just decide to hide or show the watermark textbox is enough. Though not beautiful,but work well.

提交回复
热议问题