Keeping keyboard focus on a single control while still beeing able to use a ListBox
wpf
Solution
There might be a more elegant solution for this, but you could always handle the PreviewKeyDown event at the Window level, and pass focus to the TextBox if it doesn't already have it, instead of preventing it from losing focus in the first place. That way, the ListBox can use focus as is normal, but as soon as a key is pressed focus jumps right to the TextBox. In addition, you can filter out keys that you don't want to switch focus - the arrow keys come to mind, which could then be used to move up and down in the ListBox.
Adding an event handler like the following should do the trick:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (!textBox.IsFocused)
{
textBox.Focus();
}
}
Problem
Working on a TouchScreen application which also has a keyboard attached, I have the following problem: The WPF window has a TextBox, which should receive ALL keyboard input. There are also Buttons and a ListBox, which are solely used by the TouchScreen(=Mouse). A very simple example looks like this: ``` <Window x:Class="KeyboardFocusTest.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1"> <StackPanel> <TextBox Text="{Binding Input, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus"/> <Button Click="Button_Click">Add</Button> <ListBox ItemsSource="{Binding Strings}" /> </StackPanel> </Window> ``` To keep the TextBox always focused, I just do: ``` private void TextBox_PreviewLostKeyboardFocus(object sender, System.Windows.Input.KeyboardFocusChangedEventArgs e) { e.Handled = true; } ``` So far so good - the problem now is, that I can't select items from the ListBox anymore. This only seems to work, if the ListBox has the keyboard focus. But if I loose the keyboard focus on the TextBox, I can't enter text anymore without clicking it first. Any ideas, comments suggestions are welcome!