16

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 remove the text automatically in XAML code, how do I do it?

CharithJ
  • 46,289
  • 20
  • 116
  • 131
HelloWorld1
  • 13,688
  • 28
  • 82
  • 145

8 Answers8

34

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;
}
Donut
  • 110,061
  • 20
  • 134
  • 146
  • Could you elaborate on the last line of code, please? What does it do and why is it necessary? Thank you. – Jakov Jan 25 '16 at 11:13
  • @Jakov, "You'll also want to remove the handler" -> The handler was assigned in the XAML, GotFocus="TextBox_GotFocus", this removes it so you don't lose the text the next time. – SH- Aug 15 '16 at 19:10
8

A XAML implementation that requires no code-behind. This is copied from the template of a custom control I built, and you'd probably want to make this a custom control yourself.

The basic idea is that there are two TextBoxes in a Grid. The top one is the actual control that the user interacts with, but it's invisible (its 'Opacity' is zero) unless it contains text or has the focus. The bottom one contains the prompt text. It will only be visible when the TextBox on top of it is not, and it will never get the focus.

You'll probably have to mess around with the binding on the editable TextBox, but this should get you started.

    <Grid>
      <TextBox Text="This is the prompt text"
               FontStyle="Italic"
               Foreground="LightGray"
               Focusable="False">
      </TextBox>
      <TextBox Text="{Binding TextProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
               Focusable="True">
          <TextBox.Style>
              <Style TargetType="TextBox">
                  <Setter Property="Opacity"
                          Value="1" />
                  <Style.Triggers>
                      <MultiTrigger>
                          <MultiTrigger.Conditions>
                              <Condition Property="IsFocused"
                                         Value="False" />
                              <Condition Property="Text"
                                         Value="" />
                          </MultiTrigger.Conditions>
                          <Setter Property="Opacity"
                                  Value="0" />
                      </MultiTrigger>
                  </Style.Triggers>
              </Style>
          </TextBox.Style>
      </TextBox>
  </Grid>
Robert Rossney
  • 94,622
  • 24
  • 146
  • 218
  • 1
    +1 This is a more MVVM friendly solution as it does not require any code-behind. This would also be able to be converted in to a ControlTemplate so that you could refer to this style with a key. – fatty Aug 08 '11 at 04:38
5

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;
}
CharithJ
  • 46,289
  • 20
  • 116
  • 131
3

To expound upon Donut's answer so that your textbox will keep the text a user inputs unless it's purely whitespace, here's a solution that I use:

XAML

<TextBox Text="Search..."
         Width="250"
         Foreground="LightGray"
         GotFocus="TextBox_GotFocus"
         LostFocus="TextBox_LostFocus" />

C#

void TextBox_GotFocus( object sender, RoutedEventArgs e )
{
    TextBox box = sender as TextBox;
    box.Text = string.Empty;
    box.Foreground = Brushes.Black;
    box.GotFocus -= TextBox_GotFocus;
}

void TextBox.LostFocus( object sender, RoutedEventArgs e )
{
    TextBox box = sender as TextBox;
    if( box.Text.Trim().Equals( string.Empty ) )
    {
        box.Text = "Search...";
        box.Foreground = Brushes.LightGray;
        box.GotFocus += TextBox_GotFocus;
    }
}
Meloviz
  • 571
  • 6
  • 16
0

I just did this:

XAML:

<TextBox Name="Filename"
         Grid.Column="0" 
         Height="23" 
         Margin="10,9,0,0" 
         Text="Enter Export Filename here" 
         Width="193"
         GotFocus="Filename_GotFocus"
         />

Code behind:

 private void Filename_GotFocus(object sender, RoutedEventArgs e)
        {
            Filename.Text = "";            
        }
  • 1
    Of course the popular response does as advertised in that once you start typing it will keep what you have already typed in. My answer clears the textbox each time focus has been obtained. – Petermac Aug 08 '13 at 16:39
0

I want to update Donut's answer.(applicable for windows 8)

Code behind code be

public void TextBox_GotFocus(object sender, RoutedEventArgs e)
{

   TextBox tb = (TextBox)sender;

   if(tb.Text != "SOME DEFAULT TEXT")
   {

     String persentContentWithDefaultString = t.Text as string;
     tb.Text = persentContentWithDefaultString[0].ToString();
     // set cursor position 
      tb.Select(1, 0);         

      tb.GotFocus -= TextBox_GotFocus;
 }
}

Actully in my page , there were two textbox and one button. [Username,pass,and click button]. By default , focus goes to my first textbox and User was not able to see the default text.

jee
  • 524
  • 4
  • 7
0

you can use Tap method also , it is also working

private void tb1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
    {
        tb1.Text = "";
    }
Adi
  • 903
  • 2
  • 15
  • 25
0

Please don't over complicate the answer several ways to skin a cat but, less code the better I would presume.

Petermac's option is the way to go for me.

Add "GotFocus" in the main Xaml window to the control eg."textbox"

    private void Filename_GotFocus(object sender, RoutedEventArgs e)
    {
        Filename.Text = "";            
    }

or I like this option

    private void Filename_GotFocus(object sender, RoutedEventArgs e)
    {
        Filename.clear();            
    }

the question asked was just to empty the textbox.

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335