Hello,
Welcome to Microsoft Q&A!
I want focus moved to the next ListViewItem.
To achieve such behavior, you will need to handle the KeyDown and KeyUp events of all the ListViewItems
to manually control the focus status.
First, please set the TabNavigation property of the ListView as Cycle.
<ListView x:Name="lvList" Width="200" Grid.Column="0" Margin="0,100,0,0" TabNavigation="Cycle" SelectionMode="None" >
Then you add the same the KeyDown and KeyUp event handler to all the ListViewItems
. Inside the event, you need to manually set focus when tab is pressed. Since the TextBox
will automatically receive focus if you set focus to the ListViewItem
, so we need to disable the TextBox
in KeyDown and switch it back in KeyUp .
The event code is here:
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
// set the fisrt item as focused if needed
ListViewItem Item = lvList.ContainerFromIndex(0) as ListViewItem;
Item.Focus(FocusState.Programmatic);
}
private void ListViewItem_KeyUp(object sender, KeyRoutedEventArgs e)
{
// make textbox work again.
ListViewItem currentitem = sender as ListViewItem;
TextBox targetBox = FindChild(currentitem) as TextBox;
targetBox.IsTabStop = true;
}
private void lvList_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Tab)
{
//When the tab pressed,get current item index
ListViewItem currentitem = sender as ListViewItem;
var index = lvList.IndexFromContainer(currentitem);
// then get the next item and set focus
var count = lvList.Items.Count;
if (index + 1 > count - 1)
{
//back to first item
ListViewItem nextItem = lvList.ContainerFromIndex(0) as ListViewItem;
TextBox targetBox = FindChild(nextItem) as TextBox;
targetBox.IsTabStop = false;
nextItem.Focus(FocusState.Programmatic);
}
else
{
// focus on next item
ListViewItem nextItem = lvList.ContainerFromIndex(index + 1) as ListViewItem;
TextBox targetBox = FindChild(nextItem) as TextBox;
targetBox.IsTabStop = false;
nextItem.Focus(FocusState.Programmatic);
}
}
}
public static DependencyObject FindChild(DependencyObject parant)
{
int count = VisualTreeHelper.GetChildrenCount(parant);
for (int i = 0; i < count; i++)
{
var MyChild = VisualTreeHelper.GetChild(parant, i);
if (MyChild is FrameworkElement && (FrameworkElement)MyChild is TextBox)
return MyChild;
var FindResult = FindChild(MyChild);
if (FindResult != null)
return FindResult;
}
return null;
}
Thank you.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.