방법: TextBox에 워터마크 추가

다음 예제에서는 사용자가 텍스트를 입력할 때까지 TextBox의 내부에서 설명 배경 이미지를 표시하여 TextBox의 유용성을 지원하는 방법을 보여 줍니다. 이때 이미지가 제거됩니다. 또한 사용자가 입력을 제거하면 배경 이미지가 다시 복원됩니다. 다음 그림을 참조하세요.

배경 이미지가 있는 TextBox

참고

이 예제에서 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

참고 항목