Clear text in Text box on clicking it

让人想犯罪 __ 提交于 2019-12-13 05:14:23

问题


I want my TextBox's text which has already product name on it to automatically vanishes when I click on it, and I can enter the text box I want in it.

  • The product name must be there always while there is no text in the TextBox
  • I also want that if I click on the TextBox for the second time I don't lose what I've already entered.

Please let me know how can I do it without loosing the data I've entered manually in it and I can get the default text whenever there is nothing entered by myself in the text box.


回答1:


why use some extra software and not to use your own mind to code? here is the simple code to achieve this task

first use this:

public bool txSearch = false;

then on your text click event code:

private void txtSearch_Click(object sender, EventArgs e)
{
    txSearch = true;

    if (txtSearch.Text == "Product Name")
    {
        if (txSearch == true)
        {
            txtSearch.Text = "";
        }                   
    }
}

this will clear your field text box when you click on the text, now to write back the product name when there is nothing in your textbox and you are leaving it do this code on textbox leaving event:

private void txtSearch_Leave(object sender, EventArgs e)
{
    if (txtSearch.Text == "")  // here you can also use txtSearch.Text != "Poduct Name", but it could affect your search code possibly 
    {
        txtSearch.Text = "Product Name";  
    } 
}



回答2:


That behavior is known as watermark. You can either :

  1. Use textbox control with watermark from a library such as WPF extended toolkit
  2. Implement it your self using style and attached behavior as demonstrated in this blog post
  3. Do some trick to achieve the same behavior with simpler code, for example as shown in this codeproject post



回答3:


You should consider using a third party control, there are plenty WatermarkTextbox Controls available. I prefer the one from xceed: http://wpftoolkit.codeplex.com/wikipage?title=WatermarkTextBox

I wrote this behavior by myself some time ago, used an AdornerDecorator to lay over the TextBox, bound the IsFocused Property to my ViewModel and made a flag ShouldShowWatermark in which I bound the Visibility of the AdornerDecorator.




回答4:


You actually need a watermark for your textbox.

Please look at this answer of Watermark / hint text TextBox in WPF to implement an attached property to a textbox.



来源:https://stackoverflow.com/questions/21673423/clear-text-in-text-box-on-clicking-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!