I am creating a UserControl consisting of a TextBox and a ListView . I want the keyboard focus to stay with the TextBox while the control has keyboard focus (selection changes in the ListView should not remove keyboard focus from the TextBox ).
I tried to catch GotKeyboardFocus in a ListView and pass keyboard focus to a TextBox using Keyboard.Focus(), , but this seems to cancel any selection operation in the ListView . The following code shows the problem. Does anyone know how to achieve this functionality?
<Window x:Class="WpfApplication5.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <StackPanel> <TextBox x:Name="TextBox1" /> <ListView x:Name="ListBox1" Keyboard.GotKeyboardFocus="ListBox1_GotKeyboardFocus"> <ListViewItem Content="Able" /> <ListViewItem Content="Baker" /> <ListViewItem Content="Charlie" /> </ListView> </StackPanel> </Window>
using System.Windows; using System.Windows.Input; namespace WpfApplication5 { public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void ListBox1_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { Keyboard.Focus(TextBox1); } } }
source share