Strengthen my suggestion for using a buddy.
Adorner is basically a custom-level element that appears above / around another element. For example, if you perform a check in a binding, the red frame that adorns the invalid control is the advertiser - it is not part of the control and can be applied (and applied) to all kinds of controls. See the Adorners section in WPF docs for a simple but clear example.
I thought of Adorner for several reasons. The key is that the behavior you describe may not necessarily be limited to the TextBox . You may, for example, want the ComboBox exhibit the same behavior. Adorner's implementation will give you a consistent way to implement this functionality for multiple controls (although this doesn't make sense, like CheckBox or ProgressBar ). Secondly, you donโt need to do anything with a basic control that is more complicated than implementing triggers to show and hide Adorner in response to focus events. Certificates are a bit of a pain in the butt to implement, but it is worth knowing how to do it.
All that said, I like the matte answer much more than me. The only drawbacks that I see in this approach are 1) it only works with TextBox ; you need to implement a new version of the style every time you want to use the approach on another control, 2) I can just do magic thinking, but every time I ever used the Tag property in WinForms, he told me (as soon as I learned to listen) that I was building something fragile. I am not sure for sure that this is also true in WPF, but I am sure that it is.
My comment on using the bound Text property probably needs to be amplified. If you use the Text property to store a field label, then you have a number of problems that are difficult to solve. First, since this is a related property, changing its value in a TextBox will change it in the source. So, now your source needs to know a lot of information about the state of the user interface - is there any control at the moment? If the value of the Text property is Foo , does this mean that the label is Foo or is the user entering Foo ? There are probably ways you can control this, but the best way to handle this is not necessary.
(Another issue with this paradigm: what should be the behavior if the user wants the TextBox value to be an empty string?)
source share