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