我想在按CTRL + N键的同时专注于AutocompleteBox
。我尝试了一些代码,但对我不起作用。在UserControl
控件中,我使用了PreviewKeyDown
事件,如下所示,
注意:只有在发生以下关键事件之前写MessageBox.Show("some");
时,我才会使用下面的代码
private void UserControl_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.N && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
MessageBox.Show("sfsd");
Keyboard.Focus(SearchTextBox);
SearchTextBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
e.Handled = true;
}
UserControl:
<UserControl x:Class="Inventory_Control.UserControls.SaleTab"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Inventory_Control.UserControls"
xmlns:staticData="clr-namespace:Inventory_Control.UserControls"
mc:Ignorable="d"
xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
d:DesignHeight="450" d:DesignWidth="800" Loaded="UserControl_Loaded_1" PreviewKeyDown="UserControl_PreviewKeyDown"
>
AutoCompleBox:
<controls:AutoCompleteBox Name="SearchTextBox" IsTextCompletionEnabled="True" SelectedItem="{Binding Code, Mode=TwoWay}" Grid.Column="1" PreviewKeyDown="SearchTextBox_PreviewKeyDown" Grid.Row="1" >
<controls:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Code}"/>
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</controls:AutoCompleteBox.ItemTemplate>
</controls:AutoCompleteBox>
并将用户控件上的CTRL + N键事件捕获为
private void UserControl_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.N && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
Keyboard.Focus(SearchTextBox);
SearchTextBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
e.Handled = true;
}
}
以上代码对我不起作用。请帮助
答案 0 :(得分:1)
您可以尝试使用DispatcherPriority
低于Normal
的调度程序:
private void UserControl_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.N && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
Keyboard.Focus(SearchTextBox);
SearchTextBox.Dispatcher.BeginInvoke(new Action(() =>
{
SearchTextBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}), System.Windows.Threading.DispatcherPriority.Background);
e.Handled = true;
}
}