Share via


Procedura: aggiungere una filigrana a un oggetto TextBox

Nell'esempio seguente viene illustrato come semplificare l'usabilità di un TextBox oggetto visualizzando un'immagine di sfondo esplicativa all'interno di TextBox fino a quando l'utente non inserisce testo, a quel punto l'immagine viene rimossa. Inoltre, l'immagine di sfondo viene ripristinata di nuovo se l'utente rimuove l'input. Vedere la figura seguente.

A TextBox with a background image

Nota

Il motivo per cui un'immagine di sfondo viene usata in questo esempio piuttosto che modificare semplicemente la proprietà di , è che un'immagine di TextBoxsfondo non interferisce con il Text data binding.

Esempio

Il codice XAML seguente illustra quanto segue:

<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>

Il codice seguente gestisce l'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

Vedi anche