Search code examples
c#wpflistviewfocuslistviewitem

WPF - Set Keyboard Focus to ListView Item like Tab does


I have a Listview amongst other controls in my WPF form. When I tab between controls and the ListView is focused, automatically a ListView Item is focused, not the ListView itself, which allows to move between Items with the keyboard.

I want the same behavior when a user clicks on a blank area in the ListView. So I created a Click event for the ListView, but do not know which code to execute. I have tried;

ListView.Focus();
Keyboard.Focus(ListView);

But always the ListView itself is focused, which makes sense I guess.. Setting the ListView to focusable = false completely disables focusing, including the items and focusing with tabbing around also does not work anymore.

How can I recreate the Tab focus behavior in my OnClick event?


Solution

  • You could try to focus the first item in the ListView:

    ListView.SelectedIndex = 0;
    ListViewItem lvi = ListView.ItemContainerGenerator.ContainerFromIndex(0) as ListViewItem;
    if (lvi != null)
        lvi.Focus();