0

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,
enter image description here

 <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);

            }
        }
Zohaib
  • 189
  • 1
  • 5
  • 16
  • check this link - https://stackoverflow.com/questions/1361350/keyboard-shortcuts-in-wpf – Pratius Dubey Aug 05 '18 at 05:09
  • i already tried – Zohaib Aug 05 '18 at 05:17
  • In general, `Focus` will work in the way you're seeing in the image. Do you want it to enter to *Edit* mode? Are you expecting to key in values after focusing? If so, you need to focus the `TextBox` inside your `AutoCompleteBox` – dhilmathy Aug 06 '18 at 10:45

1 Answers1

1

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);
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88