How can I put some text into a textbox which is removed automatically when user types something in it? (In WPF)
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Carriage Return (ASCII chr 13) is missing from tex
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
This technique uses the Background property to show / hide placeholder textbox.
Placeholder is shown event when Textbox has the focus
How it works:
Here is basic example. For my own purposes I turned this into a UserControl.
Here is the ValueConverter to detect non-empty strings in the DataTrigger.
You can keep a seperate value for the entered text and you can set it along with the "Text" field of the text box in the "GotFocus" and "LostFocus" events. When you get the focus, you'll want to clear the text box if there is no value. And when you loss the focus, you'll want to set the get the "Text" value from the text box and then reset the "Text" value of the text box to the place holder if it is empty.
Then you just have to make sure that the "Text" value of the text box is initialized to the place holder text.
You can further extract this into a class that extends the "TextBox" class and then reuse it through out your project.
And then this can be added in the directly in the xaml.
Also, see this answer. You can accomplish this much more easily with a VisualBrush and some triggers in a Style:
To increase the re-usability of this Style, you can also create a set of attached properties to control the actual cue banner text, color, orientation etc.
This is a sample which demonstrates how to create a watermark textbox in WPF:
TextInputToVisibilityConverter is defined as:
Note: This is not my code. I found it here, but I think this is the best approach.
Set up the text box with placeholder text in a soft color...
When the text box gets the focus, clear it and change the text color