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!

没有正确的解决方案

其他提示

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);
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top