Simple Search Textbox (with disabled text)

This is a kind of requirement in a business application; A search text box with a disabled text. I don't think I need to explain this as the code is very simple for you to understand;


Check this
public class CustomSearchTextBox : TextBox
    {
        public CustomSearchTextBox()
        {            
            this.GotFocus += (sender, e) =>
            {
                if (Text == DisabledText)
                    Text = "";
                else
                    this.SelectAll();
                Foreground = new SolidColorBrush(Colors.Black);
            };

            this.LostFocus += (sender, e) => { TrySetDisabledText(); };

            this.Loaded += (sender, e) => { TrySetDisabledText(); };
        }

        private void TrySetDisabledText()
        {
            if (string.IsNullOrEmpty(this.Text))
            {
                this.Text = DisabledText;
            }

            if (this.Text != this.DisabledText)
            {
                this.Foreground = new SolidColorBrush(Colors.Black);
            }
            else
            {
                this.Foreground = new SolidColorBrush(Colors.LightGray);
            }
        }

        public string DisabledText
        {
            get { return (string)GetValue(DisabledTextProperty); }
            set { SetValue(DisabledTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for DisabledText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DisabledTextProperty =
            DependencyProperty.Register("DisabledText", typeof(string), typeof(CustomSearchTextBox), null);
    }

 Add the above example to your code and use CustomTextBox instead of normal textbox and use DisabledText='Drivers name' to display the text

Simple

Comments