Centro
Centro

Reputation: 4012

MaxLength for AutoCompleteBox in Silverlight

I use an AutoCompleteBox control in my project. Now I need to restrict the length of text a user can enter, e.g. by the maximum length 50 characters. For this case, TextBox has the MaxLength property, but AutoCompleteBox hasn't. Also, AutoCompleteBox doesn't expose TextBox's properties.

I tried to resolve the issue in this way:

private void autoCompleteBox_TextChanged(object sender, RoutedEventArgs e)
{
        AutoCompleteBox autoCompleteBox = sender as AutoCompleteBox;
        if (autoCompleteBox.Text.Length > MaxCharLength)
        {
            autoCompleteBox.Text = autoCompleteBox.Text.Substring(0, MaxCharLength);
        }
}

A big drawback of this method is that after setting the Text property, the text box caret is reset to the start position, and when a user go on typing, characters at the end are trimmed and the caret always go to the beginning. There are no methods exposed to control the caret (like the TextBox's Select method).

Any ideas how can the maximum length be set for AutoCompleteBox?

Upvotes: 1

Views: 1115

Answers (2)

Gene Black
Gene Black

Reputation: 121

How about....

    public class CustomAutoCompleteBox : AutoCompleteBox
{
    private int _maxlength;
    public int MaxLength 
    {
        get
        {
            return _maxlength;
        } 
        set
        {
            _maxlength = value;
            if (tb != null)
                tb.MaxLength = value;
        } 
    }

    TextBox tb;
    public override void OnApplyTemplate()
    {
        tb = this.GetTemplateChild("Text") as TextBox;
        base.OnApplyTemplate();
    }
}

Upvotes: 1

Centro
Centro

Reputation: 4012

The problem can be solved by subclassing from Control class, from which AutoCompleteBox is derived, in this way:

public class AutoCompleteBoxMaxLengthed : AutoCompleteBox
{
    public int MaxLength
    {
        get;
        set;
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        if (Text.Length >= MaxLength)
        {
            e.Handled = true;
        }
        else
        {
            base.OnKeyDown(e);
        }
    }
}

Upvotes: 1

Related Questions