Silverlight中的文本框是否有任何属性,如html输入标签中的占位符?我想向用户提供一些提示,此文本框将用作输入。例如:加载页面后,TextBox中将出现一个字符串,例如“ search here ...”,并且用户单击TextBox时,该字符串就会消失,并且如果用户在单击时没有插入任何内容,则会再次出现该字符串。此文本框。
我对Johan的水印行为类进行了轻微的修改/增强,因为它不考虑文本字段由于绑定而何时更改。 (即,假设您拥有:
<TextBox Text="{Binding AccountNumber,Mode=TwoWay}">
<i:Interaction.Behaviors>
<Behaviors:Placeholder Text="Enter Account #..." Foreground="Gray" />
</i:Interaction.Behaviors>
</TextBox>
然后在您的视图模型中:
public string AccountNumber
{
get { return _accountNumber; }
set { _accountNumber = value;
RaisePropertyChanged("AccountNumber");
}
}
现在,如果在代码中的某处执行类似“ AccountNumber = string.Empty”的操作,该行为将更新水印:
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;
}
}
为了避免绑定的问题应该在Loaded事件中订阅