In this post I will implement a Default Text property for a Windows Phone 7 TextBox control. This property could be useful in such applications like Twitter, Rss Reader clients etc. Take a look at webcast bellow.
To make it possible to specify a Default Text value for a Windows Phone TextBox control we need to create a new class, inherit a TextBox and add one property and override some events. New property will hold a value for a default text. You also need to override GotFocus and LostFocus events to manipulate with text property. Here is my code for creating default text feature:
public class EDAdvancedTextbox: TextBox
{
private string _defaultText = string.Empty;
public string DefaultText
{
get
{
return _defaultText;
}
set
{
_defaultText = value;
SetDefaultText();
}
}
public EDAdvancedTextbox()
{
this.GotFocus += (sender, e) =>
{ if (this.Text.Equals(DefaultText)) { this.Text = string.Empty; } };
this.LostFocus += (sender, e) => { SetDefaultText(); };
}
private void SetDefaultText()
{
if (this.Text.Trim().Length == 0)
this.Text = DefaultText;
}
}
To specify this custom control in my XAML I have used the following line:
<local:EDAdvancedTextbox x:Name="tbSearch" DefaultText="enter username..." />



Pingback: Android Phone Q&A:How to permanently uninstall text message app on android phone? (Motorola backflip)? | What Is The Best Android Phone
Nice Blog! Thanks for this article
took off some work from me, thank you
set
{
_defaultText = value;
SetDefaultText();
what meaning?
Probably it was used to update the TextBox UI, but you can also use Data Binding instead.
You need to change some lines in order to use localization bindings:
public static readonly DependencyProperty DefaultTextProperty = DependencyProperty.Register("DefaultText", typeof(string), typeof(EAdvancedTextbox), new PropertyMetadata(""));
public string DefaultText
{
get
{
return (string)GetValue(DefaultTextProperty);
}
set
{
SetValue(DefaultTextProperty, value);
SetDefaultText();
}
}
and also add a handler for the loaded event last in the constructor:
this.Loaded += (sender, e) => { SetDefaultText(); };
Without these changes you get an exception when trying to bind values to DefaultText in your xaml files.
Thanks for the article!
Thank you!