Search code examples
c#listviewfocuswinui-3

Set focus to the first listview item


In WinUI3 I need to set focus to the first item of ListView in order user could use the keyboard immediately. I do the following:

listView.Focus(FocusState.Programmatic);

if (listView.Items.Count > 0) 
{
    listView.SelectedIndex = 0;                                     
}

But only the listview gets the focus, not the item and I need to click first on the item before I can go up and down with the keyboard. Is there any easy way to focus on the first item of the listview?


Solution

  • For some reason, ListViewItem can't be selected from the first time so here is some workaround for this problem:

    ListViewItem lvi = listView.ContainerFromIndex(0) as ListViewItem;
    
    if (lvi != null) 
    {
        lvi.IsSelected = true;
        lvi.Focus(FocusState.Programmatic);
    } 
    else 
    {
        var dispatcherQueue = DispatcherQueue.GetForCurrentThread();
        dispatcherQueue.TryEnqueue(DispatcherQueuePriority.Low,
                            () => {
                                lvi = listView.ContainerFromIndex(0) as ListViewItem;
                                if (lvi != null) {
                                    lvi.IsSelected = true;
                                    lvi.Focus(FocusState.Programmatic);
                                }
                            });
    }