C# 将占位符文本添加到文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11873378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:36:16  来源:igfitidea点击:

Adding placeholder text to textbox

c#wpfplaceholder

提问by Boardy

I am looking for a way to add placeholder text to a textbox like you can with a textbox in html5.

我正在寻找一种将占位符文本添加到文本框的方法,就像使用 html5 中的文本框一样。

I.e. if the textbox has no text, then it adds the text Enter some text here, when the user clicks on it the placeholder text disappears and allows the user to enter their own text, and if the textbox loses focus and there is still no text then the placeholder is added back to the textbox.

即如果文本框没有文本,那么它添加文本Enter some text here,当用户点击它时占位符文本消失并允许用户输入他们自己的文本,如果文本框失去焦点并且仍然没有文本那么占位符是添加回文本框。

采纳答案by ExceptionLimeCat

Wouldn't that just be something like this:

不就是这样吗:

Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";

myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);

public void RemoveText(object sender, EventArgs e)
{
    if (myTxtbx.Text == "Enter text here...") 
    {
     myTxtbx.Text = "";
    }
}

public void AddText(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(myTxtbx.Text))
        myTxtbx.Text = "Enter text here...";
}

Thats just pseudocode but the concept is there.

那只是伪代码,但概念就在那里。

回答by H.B.

You can get the default Template, modify it by overlaying a TextBlock, and use a Styleto add triggers that hide and show it in the right states.

您可以获取默认值Template,通过覆盖 a 来修改它TextBlock,并使用 aStyle添加触发器以在正确的状态下隐藏和显示它。

回答by MacGile

You can use this, it's working for me and is extremely simple solution.

您可以使用它,它对我有用,并且是非常简单的解决方案。

    <Style x:Key="placeHolder" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Grid>
                        <TextBox Text="{Binding Path=Text,
                                                RelativeSource={RelativeSource TemplatedParent}, 
                                                Mode=TwoWay,
                                                UpdateSourceTrigger=PropertyChanged}"
                                 x:Name="textSource" 
                                 Background="Transparent" 
                                 Panel.ZIndex="2" />
                        <TextBox Text="{TemplateBinding Tag}" Background="{TemplateBinding Background}" Panel.ZIndex="1">
                            <TextBox.Style>
                                <Style TargetType="{x:Type TextBox}">
                                    <Setter Property="Foreground" Value="Transparent"/>
                                    <Style.Triggers>
                                        <DataTrigger Binding="{Binding Path=Text, Source={x:Reference textSource}}" Value="">
                                            <Setter Property="Foreground" Value="LightGray"/>
                                        </DataTrigger>
                                    </Style.Triggers>
                                </Style>
                            </TextBox.Style>
                        </TextBox>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Usage:

用法:

<TextBox Style="{StaticResource placeHolder}" Tag="Name of customer" Width="150" Height="24"/>

???????????????????????????????????????

??????????????????????????????????????????

回答by CBC_NS

I came up with a method that worked for me, but only because I was willing to use the textbox name as my placeholder. See below.

我想出了一个对我有用的方法,但这只是因为我愿意使用文本框名称作为我的占位符。见下文。

public TextBox employee = new TextBox();

private void InitializeHomeComponent()
{
    //
    //employee
    //
    this.employee.Name = "Caller Name";
    this.employee.Text = "Caller Name";
    this.employee.BackColor = System.Drawing.SystemColors.InactiveBorder;
    this.employee.Location = new System.Drawing.Point(5, 160);
    this.employee.Size = new System.Drawing.Size(190, 30);
    this.employee.TabStop = false;
    this.Controls.Add(employee);
    // I loop through all of my textboxes giving them the same function
    foreach (Control C in this.Controls)
    {
        if (C.GetType() == typeof(System.Windows.Forms.TextBox))
        {
            C.GotFocus += g_GotFocus;
            C.LostFocus += g_LostFocus;
        }
     }
 }

    private void g_GotFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        tbox.Text = "";
    }

    private void g_LostFocus(object sender, EventArgs e)
    {
        var tbox = sender as TextBox;
        if (tbox.Text == "")
        {
            tbox.Text = tbox.Name;
        }
    }

回答by Abdullah Qudeer

Instead of handling the focus enter and focus leave events in order to set and remove the placeholder text it is possible to use the Windows SendMessage function to send EM_SETCUEBANNERmessage to our textbox to do the work for us.

可以使用 Windows SendMessage 函数将EM_SETCUEBANNER消息发送到我们的文本框来为我们完成工作,而不是处理焦点进入和焦点离开事件以设置和删除占位符文本 。

This can be done with two easy steps. First we need to expose the Windows SendMessagefunction.

这可以通过两个简单的步骤来完成。首先我们需要暴露WindowsSendMessage函数。

private const int EM_SETCUEBANNER = 0x1501;

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern Int32 SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]string lParam);

Then simply call the method with the handle of our textbox, EM_SETCUEBANNER's value and the text we want to set.

然后简单地使用我们的文本框的句柄、EM_SETCUEBANNER 的值和我们想要设置的文本调用该方法。

SendMessage(textBox1.Handle, EM_SETCUEBANNER, 0, "Username");
SendMessage(textBox2.Handle, EM_SETCUEBANNER, 0, "Password");

Reference: Set placeholder text for textbox (cue text)

参考:为文本框设置占位符文本(提示文本)

回答by Nalan Madheswaran

Try the following code:

试试下面的代码:

<TextBox x:Name="InvoiceDate" Text="" Width="300"  TextAlignment="Left" Height="30" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" />
                    <TextBlock IsHitTestVisible="False" Text="Men att l?sa" Width="300"  TextAlignment="Left" Height="30" Grid.Row="0" Grid.Column="3" Grid.ColumnSpan="2" Padding="5, 5, 5, 5"  Foreground="LightGray">
                        <TextBlock.Style>
                            <Style TargetType="{x:Type TextBlock}">
                                <Setter Property="Visibility" Value="Collapsed"/>
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding Text, ElementName=InvoiceDate}" Value="">
                                        <Setter Property="Visibility" Value="Visible"/>
                                    </DataTrigger>
                                    <DataTrigger Binding="{Binding ElementName=InvoiceDate, Path=IsFocused}" Value="True">
                                        <Setter Property="Visibility" Value="Collapsed"/>
                                    </DataTrigger>

                                </Style.Triggers>
                            </Style>
                        </TextBlock.Style>
                    </TextBlock>

回答by Adiii

you can also do that when the mouse clicks, let's suppose your placeholder text is "User_Name"

您也可以在单击鼠标时执行此操作,假设您的占位符文本是“User_Name”

 private void textBox1_MouseClick(object sender, MouseEventArgs e)
 {
     if(textBox1.Text == "User_Name")
          textBox1.Text = "";
 }

回答by VJamie

This would mean you have a button which allows you to do an action, such as logging in or something. Before you do the action you check if the textbox is filled in. If not it will replace the text

这意味着您有一个按钮可以让您执行操作,例如登录或其他操作。在您执行此操作之前,请检查文本框是否已填写。如果未填写,它将替换文本

 private void button_Click(object sender, EventArgs e)
 {
     string textBoxText = textBox.Text;

     if (String.IsNullOrWhiteSpace(textBoxText))
     {
         textBox.Text = "Fill in the textbox";
     }
 }

 private void textBox_Enter(object sender, EventArgs e)
 {
     TextBox currentTextbox = sender as TextBox;
     if (currentTextbox.Text == "Fill in the textbox")
     {
         currentTextbox.Text = "";
     }
 }

It's kind of cheesy but checking the text for the value you're giving it is the best I can do atm, not that good at c# to get a better solution.

这有点俗气,但检查文本中你给它的值是我能做的最好的 atm,而不是在 c# 中获得更好的解决方案。

回答by Everton Luke

txtUsuario.Attributes.Add("placeholder", "Texto");

txtUsuario.Attributes.Add("placeholder", "Texto");

回答by Jaun Lloyd

This is not my code, but I use it a lot and it works perfect... XAML ONLY

这不是我的代码,但我经常使用它并且效果很好......仅适用于 XAML

<TextBox x:Name="Textbox" Height="23" Margin="0,17,18.8,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" HorizontalAlignment="Right" ></TextBox>

<TextBlock x:Name="Placeholder" IsHitTestVisible="False" TextWrapping="Wrap" Text="Placeholder Text" VerticalAlignment="Top" Margin="0,20,298.8,0" Foreground="DarkGray" HorizontalAlignment="Right" Width="214">
  <TextBlock.Style>
    <Style TargetType="{x:Type TextBlock}">
      <Setter Property="Visibility" Value="Collapsed"/>
      <Style.Triggers>
        <DataTrigger Binding="{Binding Text, ElementName=Textbox}" Value="">
          <Setter Property="Visibility" Value="Visible"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </TextBlock.Style>
</TextBlock>