tags:

views:

19

answers:

1

I have an ItemsControl that uses a DataTemplate. The DataTemplate contains a TextBox, which can receive keyboard focus. I need to be able to move the keyboard focus from the currently focused TextBox in the DataTemplate to the next TextBox, as if the Tab key has been pressed. I've noticed that there is a UIElement.MoveFocus() method, but this begs the question as to which UIElement should be used to call the method. This is probably the reason why I haven't gotten this method to work for me... Any help would be really appreciated!

Thanks,

Andrew

+1  A: 

You should be able to call the MoveFocus method on your Window (or Page, depending on what your top-level container is).

this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

That'll tell WPF to move the focus to the next control, either using the TabIndex properties on the controls, or just moving across and down naturally to find the next logical control.

Failing that you could call MoveFocus on your ItemsControl directly (give it a name and replace the "this" with that name in the code above).

Matt Hamilton
When I try your suggestion, the focus shifts to the ItemsControl iteself, rather than the next element in the ItemsControl. I tried a variation of your suggestion, tbxWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));but it keeps moving the focus down two elements on the list instead of one. This is really strange. I have no idea why it would move two elements down on the list. If I comment the line out, it doesn't move the focus at all...
Andrew
How are you initiating the focus change? With the tab key? If so you would need to cancel the default key event by using e.Handled = true.
Josh Einstein
I should probably mention that the TextBox is bound to a property in the control, and that the method that is being called is inserting an element in the ObservableCollection<string> property when the enter key is pressed...
Andrew
Oh.... Okay. I think I see what I've done wrong. I should mark Mark's answer as correct (except that I really need the Down direction). Apparently, my control is skipping over the newly created element, since it hasn't updated in the ItemsControl when I move the keyboard focus... Thanks everyone! This was really confusing for me!
Andrew
That's odd - I didn't think ItemsControl accepted input focus by default. You could always set Focusable (or is it IsFocusable?) to falls on the ItemsControl to prevent that.
Matt Hamilton
I mean Matt's answer. My bad!
Andrew
I don't know, maybe it's because I put a TextBox in the DataTemplate...
Andrew
@Andrew Nah I've definitely used an ItemsControl with a TextBox in the DataTemplate and never had that problem. Oh well, the main thing is you've got it worked out.
Matt Hamilton