Here’s an easy-to-use watermarked textbox that you can call programmatically.
The technique only works when the textbox is contained in a grid. We position a gray textblock over the TextBox, and set IsHitTestVisible=false so that mouse events continue to be sent to the textbox below. The code is very rough and needs to be tweaked to suit your situation. On WPF I was able to put the textblock below the TextBox and make the background of the textbox transparent. On Silverlight, I had to put the textblock over the TextBox. YMMV.
Overview:
MakeWaterMark(txtServer, "server e.g. http://yourserver.gov.au:8088/");
Code:
private void MakeWaterMark(TextBox txt, string watermark)
{
TextBlock tb = new TextBlock() {
Text = watermark,
VerticalAlignment = VerticalAlignment.Top,
FontStyle = FontStyles.Italic,
Foreground = Brushes.Gray,
Height = txt.Height,
Margin = new Thickness(txt.Margin.Left+4, txt.Margin.Top+2, txt.Margin.Right, txt.Margin.Bottom),
Visibility = (txt.Text.Length > 0) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible,
IsHitTestVisible = false,
};
#if SILVERLIGHT
(txt.Parent as Grid).Children.Add(tb);
#else
(txt.Parent as Grid).Children.Insert(0, tb);
#endif
txt.Background = Brushes.Transparent;
txt.GotFocus += (s, e) =>
{
tb.Visibility = System.Windows.Visibility.Collapsed;
};
txt.LostFocus += (s, e) =>
{
tb.Visibility = (txt.Text.Length > 0) ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
};
txt.Focus();
}
The post Silverlight/WPF Watermarked TextBox appeared first on Chui's Counterpoint.