简体   繁体   中英

AutoCompleteBox Selected on CTRL + N key event but not focused

I want to focus AutoCompleteBox when on UserControl CTRL + N key pressed. I wrote Keyboard.Focus(CustomerSearch); . The problem is on pressing CTRL + N key, the AutoCompleteBox not focused but selected with dotted line as can seen in below image,
在此处输入图片说明

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

The Ctrol + N event:

private void UserControl_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.N && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
            {
                Keyboard.Focus(CustomerSearch);

            }
        }

You should focus the TextBox in the AutoCompleteBox :

private void UserControl_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.N && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
    {
        TextBox textBox = CustomerSearch.Template.FindName("Text", CustomerSearch) as TextBox;
        if (textBox != null)
            Keyboard.Focus(textBox);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM