如何:使用背景图像来帮助提高 TextBox 的可用性

更新:2007 年 11 月

下面的示例演示在用户输入文本之前,如何通过在 TextBox 的内部显示解释性背景图像来帮助提高 TextBox 的可用性。在用户输入文本时,该图像将被移除。另外,如果用户移除他们所输入的内容,背景图像会再次还原。请参见下图。

具有背景图像的 TextBox

说明:

在本示例中,之所以使用背景图像而不只是操作 TextBoxText 属性,是因为背景图像不会干扰数据绑定。

示例

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

        }

    }

}

请参见

概念

TextBox 概述

RichTextBox 概述