Reputation: 1447
Is there any property for Textbox in Silverlight like placeholder in html input Tag? I want to provide some hint to the user what this text box takes as input.. For Example: When the page is loaded there is a string in TextBox like "search here..." and as soon the user clicks into the TextBox the string disappears and it appears again if the user didn't insert something as soon as the user click out this textbox.
Upvotes: 2
Views: 2221
Reputation: 887
I made a slight modification/enhancement to Johan's watermark behavior class, because it doesn't account for when the textfield changes due to binding. (i.e. let's say you had:
<TextBox Text="{Binding AccountNumber,Mode=TwoWay}">
<i:Interaction.Behaviors>
<Behaviors:Placeholder Text="Enter Account #..." Foreground="Gray" />
</i:Interaction.Behaviors>
</TextBox>
And then in your view model:
public string AccountNumber
{
get { return _accountNumber; }
set { _accountNumber = value;
RaisePropertyChanged("AccountNumber");
}
}
Now the behavior updates the watermark if you do something like "AccountNumber = string.Empty" somewhere in your code:
public class Placeholder : Behavior<TextBox>
{
private bool _hasPlaceholder;
private Brush _textBoxForeground;
public String Text { get; set; }
public Brush Foreground { get; set; }
protected override void OnAttached()
{
_textBoxForeground = AssociatedObject.Foreground;
base.OnAttached();
if (Text != null)
SetPlaceholderText();
AssociatedObject.GotFocus += GotFocus;
AssociatedObject.LostFocus += LostFocus;
AssociatedObject.TextChanged += TextChanged;
}
private void TextChanged(object sender,
TextChangedEventArgs textChangedEventArgs)
{
if (string.IsNullOrWhiteSpace(AssociatedObject.Text) &&
FocusManager.GetFocusedElement() != AssociatedObject)
{
if (Text != null)
SetPlaceholderText();
}
}
private void LostFocus(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(AssociatedObject.Text))
{
if (Text != null)
SetPlaceholderText();
}
}
private void GotFocus(object sender, RoutedEventArgs e)
{
if (_hasPlaceholder)
RemovePlaceholderText();
}
private void RemovePlaceholderText()
{
AssociatedObject.Foreground = _textBoxForeground;
AssociatedObject.Text = "";
_hasPlaceholder = false;
}
private void SetPlaceholderText()
{
AssociatedObject.Foreground = Foreground;
AssociatedObject.Text = Text;
_hasPlaceholder = true;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.GotFocus -= GotFocus;
AssociatedObject.LostFocus -= LostFocus;
}
}
Upvotes: 2
Reputation: 15268
Here is how to do it with a behavior:
http://weblogs.asp.net/jdanforth/archive/2010/09/17/silverlight-watermark-textbox-behavior.aspx
Upvotes: 1