本文介绍了文本框 Visual Studio C# 中的真实提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 C# 在 Visual Studio 上制作 Windows 窗体应用程序,我正在尝试找到一种方法来获得真正的提示.

I'm currently making a Windows Forms Application on Visual Studio in C# and I'm trying to find a way to have a real hint.

我在网上找到了很多关于如何在那里预设一些文本的答案,有些示例甚至展示了如何将文本变灰以使其看起来像占位符,但这不是我想要的.

I've found a lot of answers online on how to have some text preset there, Some examples even show how to grey out the text to look like a placeholder, but that's not what I'm looking for.

我想要一个灰色的文本,您不必退格即可在那里输入内容.所以我希望它表现得像一个 HTML 占位符就像堆栈溢出上的搜索问答"搜索栏.

I want a grayed out text that you don't have to backspace to type something there. So I want it to behave like an HTML placeholder like the "Search Q&A" search bar on stack Overflow.

是否有一种简单的方法可以做到这一点,例如在 Visual Studio 的设计器中配置文本框的属性?

Is there an easy way to do this, like configuring a property of the textbox in the designer on Visual Studio?

推荐答案

这可能是最丑的代码,但我认为你可以改进它.

This might be the ugliest code but I think you can improve it.

下面这个类只是标准TextBox的扩展

This following class is merely an extension of the standard TextBox

 class PHTextBox : System.Windows.Forms.TextBox
    {
        System.Drawing.Color DefaultColor;
        public string PlaceHolderText {get;set;}
        public PHTextBox(string placeholdertext)
        {
            // get default color of text
           DefaultColor = this.ForeColor;
            // Add event handler for when the control gets focus
            this.GotFocus += (object sender, EventArgs e) =>
            {
                this.Text = String.Empty;
                this.ForeColor = DefaultColor;
            };

            // add event handling when focus is lost
            this.LostFocus += (Object sender, EventArgs e) => {
                if (String.IsNullOrEmpty(this.Text) || this.Text == PlaceHolderText)
                {
                    this.ForeColor = System.Drawing.Color.Gray;
                    this.Text = PlaceHolderText;
                }
                else
                {
                    this.ForeColor = DefaultColor;
                }
            };



            if (!string.IsNullOrEmpty(placeholdertext))
            {
                // change style
                this.ForeColor = System.Drawing.Color.Gray;
                // Add text
                PlaceHolderText = placeholdertext;
                this.Text = placeholdertext;
            }



        }


    }

复制/粘贴到名为 PHTextBox.cs 的新 cs 文件.

Copy/paste to new cs file entitled PHTextBox.cs.

转到您的图形设计师并添加一个文本框.转到设计器并更改文本框的 instiantion 行,如下所示:

Go to your graphic designer and add a TextBox.Go to the designer and change the instiantion line for the textbox as follow:

现在编译,但在此之前,只需确保文本框不是获得焦点的第一个元素.为此添加按钮.

Now compile but before you do, just make sure the textbox is not the first element to get the focus. Add button for that matter.

这篇关于文本框 Visual Studio C# 中的真实提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 02:02