To allow better keyboard navigation, I'd like to set the selection to the next item.

How to set the selection to the next item after deleting a listview-item.

The following image shows a XAML ListView in a Windows 10 Universal App with SelectionMode="Single". Notice how the selection is removed after deleting an item:

selection removed

To allow better keyboard navigation, I’d like to set the selection to the next item (at the selectedIndex that was just removed) after the item was removed like in the next animation:

Selection to next item

If you are looking for this too, here is a behavior to help you with that.

SelectAfterRemoveBehavior

reference behavior SDK

[TypeConstraint(typeof(ListViewBase))]
public class SelectAfterRemoveBehavior : DependencyObject, IBehavior
{
private ListViewBase _associatedObject;
private int _index;

public DependencyObject AssociatedObject
{
get { return _associatedObject; }
}

public void Attach(DependencyObject associatedObject)
{
_associatedObject = (ListViewBase)associatedObject;
_associatedObject.SelectionChanged += OnSelectionChanged;
_associatedObject.ContainerContentChanging += OnContainerContentChanging;
}

private void OnContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
{
if (args.InRecycleQueue)
{
    if (_index > _associatedObject.Items.Count - 1)
    {
        _index = _associatedObject.Items.Count - 1;
    }
    _associatedObject.SelectedIndex = _index;
}
}

private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_associatedObject.SelectedIndex > -1)
{
    _index = _associatedObject.SelectedIndex;
}
}

public void Detach()
{
_associatedObject.SelectionChanged -= OnSelectionChanged;
_associatedObject.ContainerContentChanging -= OnContainerContentChanging;
}
}

And apply it to your ListView or GridView like this:

<ListView SelectionMode="Single" x:Name="lijst" Margin="20">
<interactivity:Interaction.Behaviors>
<local:SelectAfterRemoveBehavior />
</interactivity:Interaction.Behaviors>
</ListView>

Download a demo project or only the set-selection-behavior

Written by Loek van den Ouweland on 2015-11-09.
Questions regarding this artice? You can send them to the address below.