I have a listbox where the Items are Textboxes. I need to set a key to change the focus to the next textbox and begin the editing of its content.
I have cheated a solution sending Key strokes to achieve what I want, for example:
((TextBox)listBox1.Items[0]).KeyDown += (object x, KeyEventArgs y) => {
if (y.Key == Key.Enter) {
InputSimulator.SimulateKeyDown(VirtualKeyCode.TAB);
InputSimulator.SimulateKeyPress(VirtualKeyCode.DOWN);
InputSimulator.SimulateKeyDown(VirtualKeyCode.TAB);
}
};
I use the library InputSimulator found here http://inputsimulator.codeplex.com/ for that approach.
I know that this is not the correct way to do it so I’m ask how can i achieve the same using the focus methods. I try with the following code but i get “out of range” error that I don’t understand:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 3; i++)
{
listBox1.Items.Add(new TextBox() {
TabIndex=i
});
}
for (int i = 0; i < listBox1.Items.Count-1; i++)
{
((TextBox)listBox1.Items[i]).KeyDown += (object x, KeyEventArgs y) => { if (y.Key == Key.Tab) { Keyboard.Focus((TextBox)listBox1.Items[i+1]); } };
}
((TextBox)listBox1.Items[listBox1.Items.Count - 1]).KeyDown += (object x, KeyEventArgs y) => { if (y.Key == Key.Tab) { Keyboard.Focus((TextBox)listBox1.Items[0]); }};
}
Here is a really short answer for you. In XAML you can use a style to define a common handler for your listboxes…
So you can see all of the text boxes in the list. The actual handler code will look like this…
So the basic concept is that you will locate the current text box in the list. Then you will find the next one somehow (tags, names, etc.) and focus it explicitly. Of course you will have to tweak depending on your exact need.