Share via


Comment : faciliter l'utilisation d'un TextBox à l'aide d'une image d'arrière-plan

Mise à jour : novembre 2007

L'exemple suivant indique comment faciliter l'utilisation d'un TextBox en affichant une image d'arrière-plan explicative dans le TextBox jusqu'à ce que l'utilisateur entre du texte, après quoi l'image est supprimée. De plus, l'image d'arrière-plan est restaurée si l'utilisateur supprime son entrée. Voyez l'illustration ci-dessous.

TextBox avec image d'arrière-plan

Remarque :

Cet exemple utilise une image d'arrière-plan au lieu de simplement manipuler la propriété Text du TextBox, parce qu'une image d'arrière-plan n'interfère pas avec la liaison de données.

Exemple

<Page
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://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>
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace SDKSample
{
    public partial class TextBoxBackgroundExample : Page
    {

        void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
        {

            if (myTextBox.Text == "")
            {
                // Create an ImageBrush.
                ImageBrush textImageBrush = 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 = null;
            }

        }

    }

}

Voir aussi

Concepts

Vue d'ensemble de TextBox

Vue d'ensemble de RichTextBox