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 资料的方法
I ran into a bit of difficulty when using @john-myczek's code with a bound TextBox. As the TextBox doesn't raise a focus event when it's updated, the watermark would remain visible underneath the new text. To fix this, I simply added another event handler:
This library has a watermark.
Nuget package
Sample usage:
you can use
GetFocus()
andLostFocus()
events to do thishere is the example:
You can create a watermark that can be added to any
TextBox
with an Attached Property. Here is the source for the Attached Property:The Attached Property uses a class called
WatermarkAdorner
, here is that source:Now you can put a watermark on any TextBox like this:
The watermark can be anything you want (text, images ...). In addition to working for TextBoxes, this watermark also works for ComboBoxes and ItemControls.
This code was adapted from this blog post.
I saw John Myczek's solution, and its comments about Compatibility to
ComboBox
andPasswordBox
, so I improved John Myczek's solution, and here it is:Now, a
ComboBox
can be alsoEditable
, andPasswordBox
can add a watermark too. Don't forget to use JoanComasFdz's comment above to solve the margin problem.And, of course, All the credit goes to John Myczek.
MahApps.Metro for WPF has a built-in watermark control, if you'd rather not roll your own. It's fairly straightforward to use.