方法: TextBox へのウォーターマークの追加

次の例では、TextBox 内に説明のための背景画像を表示し、ユーザーがテキストを入力すると消えるようにすることで、TextBox の利便性を向上させる方法を示しています。 また、ユーザーが入力を削除すると、背景画像が再び表示されます。 次の図を参照してください。

A TextBox with a background image

Note

この例で、TextBoxText プロパティを操作するのではなく、背景画像が使用されているのは、背景画像がデータ バインディングに干渉しないという理由からです。

次の XAML は、次の内容を示しています。

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

次のコードは、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

関連項目