AutoCompleteBox在CTRL + N键事件上选择但未聚焦

时间:2018-08-05 04:58:47

标签: c# wpf

在按UserControl CTRL + N键时,我想将AutoCompleteBox聚焦。我写了Keyboard.Focus(CustomerSearch);。问题在于按下CTRL + N键时,AutoCompleteBox没有聚焦,而是用虚线选中,如下图所示,
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>

Ctrol + N事件:

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

            }
        }

1 个答案:

答案 0 :(得分:1)

您应该将TextBox放在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);
    }
}