Remove text after clicking in the textbox

后端 未结 8 894
孤独总比滥情好
孤独总比滥情好 2021-02-02 18:03

When you activate an application, a textbox with text \"hello\" will appear.

My question is:
When you click on the textbox in order to make input data, I want to rem

相关标签:
8条回答
  • 2021-02-02 18:36

    You have to implement both GetFocus and LostFocus events. In this way you can set the default text back in lost focus event if no text is entered.

    private const string defaultText = "Hello";
    
    private void myTextBox_GotFocus(object sender, RoutedEventArgs e)
    {
       myTextBox.Text = myTextBox.Text == defaultText ? string.Empty : myTextBox.Text;
    }
    
    private void myTextBox_LostFocus(object sender, RoutedEventArgs e)
    {
       myTextBox.Text = myTextBox.Text == string.Empty ? defaultText : myTextBox.Text;
    }
    
    0 讨论(0)
  • 2021-02-02 18:43

    Handle the UIElement.GotFocus event, and in the handler, clear the text. You'll also want to remove the handler, so that if you click on the TextBox a second time you don't lose what you've already entered.

    Something like this:

    XAML:

    <TextBox Text="Hello" GotFocus="TextBox_GotFocus" />
    

    Code-behind:

    public void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
       TextBox tb = (TextBox)sender;
       tb.Text = string.Empty;
       tb.GotFocus -= TextBox_GotFocus;
    }
    
    0 讨论(0)
提交回复
热议问题