Cómo: Agregar una marca de agua a un TextBox

En el ejemplo siguiente se muestra cómo mejorar la facilidad de uso de un control TextBox mediante una imagen de fondo explicativa dentro de TextBox hasta que el usuario escriba texto, momento en el que se quita la imagen. Además, la imagen de fondo se restaura de nuevo si el usuario quita su entrada. Vea la ilustración siguiente.

TextBox con una imagen de fondo

Nota

La razón por la que se usa una imagen de fondo en este ejemplo en lugar de simplemente manipular la propiedad Text de TextBox, es que una imagen de fondo no interferirá con el enlace de datos.

Ejemplo

En el XAML siguiente se muestra lo siguiente:

<Window x:Class="watermark.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <ImageBrush x:Key="watermark" ImageSource="textboxbackground.gif" AlignmentX="Left" Stretch="None" />
    </Window.Resources>
    <StackPanel>
        <TextBox Name="myTextBox" TextChanged="OnTextBoxTextChanged" Width="200" Background="{StaticResource watermark}" />
    </StackPanel>
</Window>

El siguiente código controla el evento TextBox.TextChanged:

private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
    if (sender is TextBox box)
    {
        if (string.IsNullOrEmpty(box.Text))
            box.Background = (ImageBrush)FindResource("watermark");
        else
            box.Background = null;
    }
}
Private Sub OnTextBoxTextChanged(sender As Object, e As TextChangedEventArgs)
    If TypeOf sender Is TextBox Then
        Dim box As TextBox = DirectCast(sender, TextBox)

        If String.IsNullOrEmpty(box.Text) Then
            box.Background = DirectCast(FindResource("watermark"), ImageBrush)
        Else
            box.Background = Nothing
        End If
    End If
End Sub

Consulte también