Question

I want to programmatically focus on an AutoCompleteBox and set its caret position just like a TextBox. We can do this on a TextBox with the Select(int, int) method but AutoCompleteBox doesn't have this. Can we extend AutoCompleteBox to achieve this? I'm using C#. Thanks!

No correct solution

OTHER TIPS

You can either extend the AutoCompleteBox class or simply get the TextBox directly in your code and call the Select method.

The TextBox in the default template of AutoCompleteBox is named "Text", so you can either call yourAutoCompleteBox.Template.FindName("Text", yourAutoCompleteBox) to get the TextBox, or create a derived class like this:

public class AutoCompleteBoxEx : AutoCompleteBox
{
    private TextBox _textBox;

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        if (Template == null) return;
        _textBox = Template.FindName("Text", this) as TextBox;
    }

    public void Select(int start, int length)
    {
        if (_textBox == null) return;
        _textBox.Select(start, length);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top