I recently was working on some code where I needed to add a watermark to my WPF TextBox. Now this is not built-in functionality. So i thought of implementing a similar functionality myself. It is quite straightforward to implement this really.
There are a few ways you could do this:
- You could overlay a TextBlock or Label with the TextBox. Then you bind the watermark to the TextBlock/Label. Finally, you toggle the visibility of the TextBlock based on the contents of the TextBox.
- Another way to do it, which is really an enhancement over the way described above is to update the ControlTemplate for the TextBox through a custom style, and put the TextBlock and TextBox in it as described above.
- Yet another way to do this would be to create a custom control which inherits from the TextBox control and overrides the OnApplyTemplate method to use the custom ControlTemplate that contains the overlayed TextBlock/Label and TextBox.
I'm not going to write the code that actually does this, since there are a few pages that describe these techniques in detail. Here are a few links that might help you.
- Watermark / hint text TextBox in WPF
- A WatermarkTextBox in 3 lines of XAML
- You could use the Extended WPF Toolkit which has this control, if you are not inclined on implementing it yourself.
Happy coding!