This tutorial is a walkthrough of creating a Watermark TextBox in Windows Phone 8. A Watermark TextBox looks as in the following. You use a Watermark TextBox in your app if you want to display readable text to the user such that they can enter desired information in that specific TextBox. In the following app these two Watermark TextBoxes are giving the information that the user should enter a Name and Phone in the first and second TextBoxes respectively.
Let us learn how to create a Watermark TextBox.
Step 1
Create two text boxes and set the text property of the TextBoxes as the watermark text. Since we want to display the Name and Phone as watermark text of the two TextBoxes we have set the Text property as the Name and Phone respectively.
- <TextBox x:Name="txtName"
- Text="Name"
- GotFocus="txtName_GotFocus"
- LostFocus="txtName_LostFocus"
- />
-
- <TextBox x:Name="txtPhone"
- Text="Phone"
- GotFocus="txtName_GotFocus"
- LostFocus="txtName_LostFocus"
- />
I have also set the GotFocus and LostFocus events of the TextBoxes.
Step 2
In the Watermark TextBox when the user clicks the TextBox a prepopulated value should be erased and the user can type in a new value. In Windows Phone 8 for a TextBox the GotFoucs event is fired when the user selects the TextBox, so on GotFocus we need to do the following two tasks:
- Erase prepopulated task
- In the case that user has left a TextBox without a value then again set TextBox text with the previously prepopulated value.
- string data;
- private void txtName_GotFocus(object sender, RoutedEventArgs e)
- {
-
- TextBox t = sender as TextBox;
- data = t.Text;
- t.Text = string.Empty;
-
- }
In the code snippet above we are typecasting as TextBox and then setting its Text property to string.empty. Before setting the value to empty we are saving the existing text value such that if the user leaves the TextBox control without inserting any value then the previous value can be used to prepopulate the TextBox.
Step 3
Assume that user clicked or touched TextBox but did not type any value and went away. In this case pervious value should get prepopulated in TextBox. So to do this when user will navigate from control we need to check that whether TextBox contains any value. If TextBox text is empty then we will set text property to previous value. This can be done as below,
- private void txtName_LostFocus(object sender, RoutedEventArgs e)
- {
- TextBox t = sender as TextBox;
- if (t.Text.Equals(string.Empty))
- {
- t.Text = data;
- }
-
- }
This is what you all need to do to create a Watermark TextBox in Windows Pone 8. I hope this article is useful. See the demo of the control below.