如何专注于AutoCompleteBox

时间:2018-08-01 15:35:12

标签: c# wpf

如何专注于AutoCompleteBox?我已经通过搜索stackover尝试了很多代码,但没有获得焦点。这是我写的一些代码。

        <controls:AutoCompleteBox Name="SearchTextBox" IsTextCompletionEnabled="True" SelectedItem="{Binding Code, Mode=TwoWay}" Grid.Column="1" PreviewKeyDown="SearchTextBox_PreviewKeyDown"  >
            <controls:AutoCompleteBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Code}"/>
                        <TextBlock Text="{Binding Name}"/>
                    </StackPanel>
                </DataTemplate>
            </controls:AutoCompleteBox.ItemTemplate>
        </controls:AutoCompleteBox>

为了重点,我创建了一个名为FocusableAutoCompleteBox的类

public class FocusableAutoCompleteBox : AutoCompleteBox
    {
        public new void Focus()
        {
            var textbox = Template.FindName("SearchTextBox", this) as AutoCompleteBox;
            if (textbox != null) textbox.Focus();
        }
    }

并关注

new FocusableAutoCompleteBox().Focus();

但出现错误

  

对象引用未设置为对象的实例

我也尝试了SearchTextBox.Focus();,但没有得到结果。

1 个答案:

答案 0 :(得分:0)

这对我有用。

Keyboard.Focus(SearchTextBox);
                SearchTextBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));