Horizontal swiping in ListViewBase control with mandatory, centered snap points.

You might need to implement a swiping behavior in a list similar to FlipView control. In FlipView, a swiping always ends at the center of an element. Unlike it works by default in ListViewBase control, where user can see many items at once and stopping points are randomly chosen. But FlipView is not really wanted, when it’s required to display left and right items. The behavior I needed to achieve:

Swiping behavior

 

Snap points type and alignment.

The easiest way to customize user interactions with a list is to configure ScrollViewer control. ScrollViewer has two properties, which allow to control horizontal swiping. It’s ScrollViewer.HorizontalSnapPointsType and ScrollViewer.HorizontalSnapPointsAlignment. MandatorySingle snap points type with Center alignment makes ScrollViewer always stop at the center of a list element.

 

Customizing horizontal swiping in GridView.

HorizontalSnapPointsType and HorizontalSnapPointsAlignment are not attached properties. They can’t be easily accessed from GridView.

Template of GridView is the best place to set MandatorySingle and Center values for internal ScrollViewer:


I also override ItemsPanel in this XAML, because I want to show items in a horizontal panel.

 

Example.

Take a look at the example here. Launch the app at Windows mobile emulator and hit Snap points example button. As soon as the next page is being loaded and a list with images is being shown, swipe to the second item and immediately to the first one. You will notice a bug. The first item becomes unreachable. I fixed the issue with inserting empty items in the beginning and the end of the list:

GridView.ScrollIntoView() allows to make the first not empty item logically focused:

To make the example works fine, go to HorizontalSnapPointsPage.xaml.cs and undo commented InsertEmptyItems() and ScrollToFirstItem() methods. Swiping in the list works as expected now.

Wish you fruitful coding!


Leave a Reply