Bastiaan
Bastiaan

Reputation: 736

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?

Upvotes: 1

Views: 2005

Answers (1)

mm8
mm8

Reputation: 169420

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();

Upvotes: 6

Related Questions