Set Focus to ListView WPF

Is there a way to execute this function from WinForms to WPF?

ListView.FocusedItem = ListView.Items[itemToFocusIndex] 

I am trying to manually set focus (not select) for an item in a WPF ListView. From System.Windows.Controls. Thanks.

+7
source share
5 answers

There are two types of focus in WPF: keyboard focus and logical focus. This link can provide you more information about focus in WPF.

You can do it:

 ListViewItem item = myListView.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem; item.Focus(); 

You can also call

 Keyboard.Focus(item); 

If you also want to scroll the ListView to a position position, add this:

 myListView.ScrollIntoView(item); 

IMPORTANT NOTE: To do this, you need to set VirtualizingStackPanel.IsVirtualizing="False" on the ListView , which may lead to its slow execution. The reason this nested property is required is because when the ListView virtualized (by default it is), ListViewItems not created for items that are not displayed on the screen, which will cause ContainerFromIndex() to return null .

+18
source

I believe that you can use Keyboard.FocusedElement to get the focused element in the list.

 Keyboard.FocusedElement 

should return a focused element

0
source
  public void foucusItem( ListView.Item itemToFocusIndex){ int count = 0; foreach(ListView.Item item in YourListView){ if(item == itemsToFocusIndex){ ListView.Items[count].Focus(); return; } count++; } } 
0
source
 //to set focus write CollistView7.Items[TheIndItem].Selected = true; CollistView7.Select(); CollistView7.Items[TheIndItem].Focused = true; //when TheIndItem is the index 
0
source

ListView elements are UIElements, so just use UIElement.Focus() . e.g. listViewItem.Focus() or button.Focus() , etc.

0
source

All Articles