共用方式為


HOW TO:使用背景影像增加 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 概觀