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!

Pas de solution correcte

Autres conseils

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);
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top