如何在WPF中轻松地将文本框更改为水印文本框

本文关键字:文本 WPF | 更新日期: 2023-09-27 18:20:26

将此TextBox代码更改为水印TextBox的最简单方法是什么?

<TextBox Grid.Column="1" Name="txtBoxAddress" Width="200" GotKeyboardFocus="TxtBoxAddress_GotKeyboardFocus" Text="" KeyUp="TxtBoxAddress_KeyUp"></TextBox>

如何在WPF中轻松地将文本框更改为水印文本框

选项一是使用MSDN中描述的背景图像。如果您想使用绑定,这可能是最好的方法。

XAML

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

或者,您可以使用BooleanToVisibilityConverter,如本代码项目文章中所述。