I want to focus into AutocompleteBox
when CTRL+N keys pressed. I've try some code but didn't works for me. In UserControl
control, i've used PreviewKeyDown
event as below,
Note: i gets focused using below code only when write MessageBox.Show("some");
before key event as below,
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>
and capture CTRL+N key event on usercontrol as,
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;
}
}
the above code not works for me.kindly help
You could try to use the dispatcher with a DispatcherPriority
lower than 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;
}
}
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.