0

Is it possible to add a "default" text value to a TextBox in WPF, with the text disappearing when the user clicks on the control or types anything in it ?

If it's not possible, how would I create a template which allows a user to define a text box with distinct properties for the content of the control and its initial value?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Hussein Khalil
  • 1,585
  • 2
  • 25
  • 47
  • 3
    duplicate question - see here: http://stackoverflow.com/q/833943/76051 – Random Dev Sep 16 '11 at 18:39
  • 1
    Use water mark for this purpose. Check this link http://windowsclient.net/blogs/swt62/archive/2009/05/10/wpf-textbox-watermark-the-easy-way.aspx and also this link http://www.c-sharpcorner.com/UploadFile/dpatra/WatermarkTextBoxInWPFApplication07272009143315PM/WatermarkTextBoxInWPFApplication.aspx – Emaad Ali Sep 16 '11 at 18:39
  • Thank you, I wasn't familiar with the term. Much appreciated. – Hussein Khalil Sep 16 '11 at 18:47
  • *Simple Solution:* If you just want to add **"add a 'default' text value to a Textbox in WPF"** you can use "SelectedText" property; And for **"text disappearing when the user clicks on the control or types anything in it"**, you can code it in TextChanged event; – Dinesh Kumar P Dec 20 '14 at 06:51
  • You can use watermark textbox for it. See the below link: [http://stackoverflow.com/questions/13406286/how-do-i-set-the-default-text-of-a-textbox-with-a-binding-of-relativesource-self][1] – Tk1993 Sep 16 '16 at 06:32

1 Answers1

4

This is certainly possible. You can either:

1) Set the initial text normally, then on an event such as OnClick() or OnTextSelected() you can delete that text, then it will be blank before they start typing. You can also go one step further and add something to OnTextChanged() to see whether the text is blank and every time there is no content, your initial content can be set again.

2) Alternatively, you can create a custom style for your text block, with a text block inside of it, a property to set the text block text and an event hooked up to clear the text block text. This is nicer, but more work. I would recommend this if you wish to re-use this control.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Ty Rozak
  • 471
  • 6
  • 19