Home >Backend Development >C++ >How to Create a TextBox Watermark Using Attached Properties in WPF?

How to Create a TextBox Watermark Using Attached Properties in WPF?

Susan Sarandon
Susan SarandonOriginal
2025-01-29 22:51:10218browse

How to Create a TextBox Watermark Using Attached Properties in WPF?

Use additional attributes to create TextBox watermark

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn