Export (0) Print
Expand All

How to: Add a Watermark to a TextBox

The following example shows how to aid usability of a TextBox by displaying an explanatory background image inside of the TextBox until the user inputs text, at which point the image is removed. In addition, the background image is restored again if the user removes their input. See illustration below.

A TextBox with a background image
NoteNote

The reason a background image is used in this example rather then simply manipulating the Text property of TextBox, is that a background image will not interfere with data binding.


<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="SDKSample.TextBoxBackgroundExample"
  >

  <StackPanel>
    <TextBox Name="myTextBox" TextChanged="OnTextBoxTextChanged" Width="200">
      <TextBox.Background>
        <ImageBrush ImageSource="TextBoxBackground.gif" AlignmentX="Left" Stretch="None" />
      </TextBox.Background>
    </TextBox>
  </StackPanel>
</Page>




Namespace SDKSample
    Partial Public Class TextBoxBackgroundExample
        Inherits Page

        Private Sub OnTextBoxTextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)

            If myTextBox.Text = "" Then

                ' Create an ImageBrush.
                Dim textImageBrush As New ImageBrush()

                textImageBrush.ImageSource =
                    New BitmapImage(New Uri("TextBoxBackground.gif", UriKind.Relative))
                textImageBrush.AlignmentX = AlignmentX.Left
                textImageBrush.Stretch = Stretch.None

                ' Use the brush to paint the button's background.
                myTextBox.Background = textImageBrush

            Else

                myTextBox.Background = Nothing
            End If

        End Sub

    End Class

End Namespace


Show:
© 2014 Microsoft