In my application the user can add items to a ListBox. I wanted the user to be able to add a new item after selecting it from the AutoCompleteBox, by pressing the Return Key once more. I thought that setting the IsDefault property to True on the Add button would’ve been enough.
This is how the MainWindow code looks like:
<ListBox Name="listBox1" />
<Button Name="button1" Content="Add" IsDefault="True" Click="button1_Click" />
<my:AutoCompleteBox Name="autoCompleteBox1"
IsTextCompletionEnabled="True"
PreviewKeyDown="autoCompleteBox1_PreviewKeyDown"/>
As setting IsDefault didn’t work because the AutoCompleteBox kept focus for itself, I then tried to respond to the KeyDown event by checking if it was the Return Key that was pressed and try to set focus to the button.
But pressing the Return Key after selecting an item didn’t fire the KeyDown event. So I finally subscribed to the PreviewKeyDown event and do this:
public partial class MainWindow : Window
{
ObservableCollection<string> myCollection = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
listBox1.ItemsSource = myCollection;
autoCompleteBox1.ItemsSource = new string[] { "item1", "item2", "item3", "item4", "item5" };
}
private void autoCompleteBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
button1.Focus();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (autoCompleteBox1.SelectedItem != null)
myCollection.Add((string)autoCompleteBox1.SelectedItem);
}
}
But the button doesn’t get the focus. How can I move focus away from the AutoCompleteBox?
Use the KeyUp event. KeyDown is too early in the cycle for changing focus.