Hi,
I have a custom control, consisiting of a textbox and a popup with a listview control. When the user enters some text in the tb, and hits enter, the popup is shown.
When the popup is opened, the textbox gives it focus. The user has to hit a key (up, down++) twice on the first hit, inorder to move focus on the listviewitems.
How can I prevent this, and make the first item in the listview to gain focus when it is shown?
I found some code that seemed very unsafe:
Focusing the first element in the lv:
private void FocusList() { if (_listview.SelectedIndex == -1) _listview.SelectedIndex = 1; ListViewItem i = _listview.ItemContainerGenerator.ContainerFromIndex(_listview.SelectedIndex) as ListViewItem; if (i != null) Keyboard.Focus(i); else _listview.Focus(); }
Called when the popup is opened.
private void PopupOpened(EventArgs args) { if (_listview == null) return; ... if (enterClicked) { Dispatcher.BeginInvoke(new Action(FocusList), System.Windows.Threading.DispatcherPriority.ApplicationIdle); //Dispatcher.BeginInvoke(new Action(FocusList), System.Windows.Threading.DispatcherPriority.Input); } }
This is really unstable. I've googled alot to no avail. What's the correct approuch for just setting focus on the first element in this list?
NB: If it's not a listview in this list, but instead a textbox, I don't have this issue. Calling .Focus() works just fine then.
Brgds,
Stian