The ramblings of web developer Beau Brownlee

 
June 2nd, 2010

One of the things I needed recently is a simple way to have a textbox that had a watermark in it. Apparantly SilverLight 4 provides it,,, and it doesn’t provide it. Check this post out. I really couldn’t help but laugh when I saw this. ‘Do not use in a Silverlight 4 application.’ and at the same time the supported version is only Silverlight 4. Aaah yes, well the only other solution is to use a watermark textbox someone else has created or to make your own. I opted to make my own. Before we get into the code here it is:

This just gives you a basic idea of what you can do. The first textbox is the user control that has watermark capabilities. If you click on the water marked textbox it will clear it out and be ready for input. If you do not type in any text and leave it blank and click on the second textbox it will replace the watermark. If you click the ‘Get Text’ button it will show blank because you do not want the watermark to count as valid text. If you click ‘Set Text’ it will programatically set the text in the textbox and you will notice that the watermark disappears.

If you like it so far,,, read on

I always like seeing demos before deciding if I want to spend time looking through code so there was the demo. If you don’t feel like reading the rest of this article and you just want the code you can download it here ;) . Now lets dig into code. This is just a user control that allows you to re-size a textbox just like you normally would with any other textbox. Here’s the interface:

<UserControl x:Class="TestSilverlightApp.WaterMarkTextbox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="23" d:DesignWidth="100">
 
 
   <TextBox HorizontalAlignment="Stretch" Loaded="textBox1_Loaded" Name="textBox1" VerticalAlignment="Stretch" Width="Auto" Height="auto"   />
 
</UserControl>

Notice the textbox is just sitting within the control container without a grid or a stackpanel and the HorizontalAlignment and VerticalAlignment are both set to ‘Stretch’ and the Width/Height are set to ‘Auto’. This tells the textbox to re-size itself along with the user control. Our C# code looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
 
namespace TestSilverlightApp
{
    public partial class WaterMarkTextbox : UserControl
    {
        private string watermark;
        public string WaterMark
        {
            set
            {
                watermark = value;
            }
 
            get
            {
                return watermark;
            }
        }
 
        public string Text
        {
            get
            {
                if (textBox1.Text == this.watermark)
                {
                    return "";
                }
                else
                {
                    return textBox1.Text;
                }
            }
            set
            {
                DisableWaterMark();
                textBox1.Text = value;
            }
        }
 
        public WaterMarkTextbox()
        {
            InitializeComponent();
        }
 
        private void SetWaterMark()
        {
            textBox1.Foreground = new SolidColorBrush(Colors.LightGray);
            textBox1.Text = this.watermark;
        }
 
        void textBox1_LostFocus(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                SetWaterMark();
                textBox1.GotFocus += new RoutedEventHandler(textBox1_GotFocus);
            }
        }
 
        private void DisableWaterMark()
        {
            textBox1.Text = "";
            textBox1.GotFocus -= textBox1_GotFocus;
            textBox1.Foreground = new SolidColorBrush(Colors.Black);
        }
 
        void textBox1_GotFocus(object sender, RoutedEventArgs e)
        {
            DisableWaterMark();
        }
 
        private void textBox1_Loaded(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(this.watermark))
            {
                textBox1.GotFocus += new RoutedEventHandler(textBox1_GotFocus);
                textBox1.LostFocus += new RoutedEventHandler(textBox1_LostFocus);
                SetWaterMark();
            }
        }
    }
}

Notice we have 2 public properties: WaterMark and Text. WaterMark is what we end up using to set the default water mark in the textbox and Text emulates what we would normally use to set Text. To use this control we simply do the following:

<my:WaterMarkTextbox WaterMark="test watermark" HorizontalAlignment="Left" x:Name="waterMarkTextbox1" VerticalAlignment="Top" Width="158" />

Pretty simple. The rest of the methods are pretty simple to follow. We simply capture events of when the textbox is focused and erase the water mark by setting the Text to “” and then change the color to black instead of grey. When we’ve lost focus on the textbox we need to see if the Text property is null or empty and if so we would then replace the watermark and tell the textbox to listen to the event GotFocus. Also notice the events are initially set in the ‘Loaded’ event. This ensures that we have set the custom property WaterMark before we start listening to events or set the initial watermark.

Download Project

WaterMark TextBox.zip

Tags: ,

Leave a Reply

You must be logged in to post a comment.


cheap software