Before the user input, it is very useful to provide users with guidance or placeholder text. At this time, it is particularly important to create a watermark in TextBox. When the user starts input, this text will disappear automatically.
Create watermarks with additional attributes
To create a watermark, you can use additional attributes and the WaterMarkadorner class provided below:
Use watermark
<code class="language-csharp">/// <summary> /// 提供水印附加属性的类 /// </summary> public static class WatermarkService { /// <summary> /// 水印附加依赖属性 /// </summary> public static readonly DependencyProperty WatermarkProperty = DependencyProperty.RegisterAttached( "Watermark", typeof(object), typeof(WatermarkService), new FrameworkPropertyMetadata((object)null, new PropertyChangedCallback(OnWatermarkChanged))); // ... }</code>
<code class="language-csharp">/// <summary> /// 水印装饰器 /// </summary> internal class WatermarkAdorner : Adorner { // ... }</code>
After defining these classes, you can use the following code to add the watermark to any Textbox:
Please note that this watermark can be applied to other controls, including Combobox and ItemControls.The above is the detailed content of How to Create a TextBox Watermark Using Attached Properties in WPF?. For more information, please follow other related articles on the PHP Chinese website!