Silverlight中文本框的占位符行为

时间:2012-01-30 12:08:08

标签: silverlight

Silverlight中的Textbox是否有像html输入Tag中的占位符一样的属性? 我想提供一些提示给用户这个文本框作为输入的内容.. 例如: 加载页面时,TextBox中有一个字符串,如“在这里搜索...”,一旦用户点击进入TextBox,字符串就会消失,如果用户在用户点击后没有插入内容,它就会再次出现这个文本框。

2 个答案:

答案 0 :(得分:2)

我对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;
    }
}

答案 1 :(得分:1)

相关问题