Calculate the horizontal offset to scroll the ListView to the center of SelectedItem

I am creating a photo application using FlipView and listView as pagination. When I click on the thumbnail in listView , it shows me the same picture in FlipView . And when I FlipView into FlipView , any selected photo will select the same image in listView . This is done by adding both of them:

In listView :

 SelectedIndex="{Binding Path=SelectedIndex, ElementName=flipView1, Mode=TwoWay} 

And to FlipView :

 SelectedIndex="{Binding Path=SelectedIndex, ElementName=listView1, Mode=TwoWay} 

And to the ListView SelectionChanged event, I added:

  if (e.AddedItems.Count > 0) listView1.ScrollIntoView(e.AddedItems.First(), ScrollIntoViewAlignment.Leading); 

My only problem is that when I scroll through FlipView , the desired snapshot is selected in listView , but ScrollViewer does not scroll. I tried using WinRTXamlToolkit to reposition ScrollViewer :

 private void pageRoot_Loaded() { // count number of all items int itemCount = this.listView1.Items.Count; if (itemCount == 0) return; if (listView1.SelectedIndex >= itemCount) listView1.SelectedIndex = itemCount - 1; // calculate x-posision of selected item double listWidth = this.listView1.ActualWidth; double xPos = (listWidth / itemCount) * listView1.SelectedIndex; // scroll var scrollViewer2 = listView1.GetFirstDescendantOfType<ScrollViewer>(); if (scrollViewer2 != null) scrollViewer2.ChangeView(xPos, 0.0, 1); } 

The first time listWidth is 1600.0 , and then it becomes 0.0 all the time, which gives xPos = 0.0 !

How can i fix this?

+6
source share
2 answers
0
source

ListView.ScrollIntoView() should work. There may be problems calling the method to scroll the ScrollViewer while it is already scrolling. I would try fiddling with ScrollViewer.InvalidateScrollInfo() , which could speed it up. Otherwise, you can try to handle ViewChanging/ViewChanged events to see if it scrolls and try to use this information along with ScrollViewerViewChangedEventArgs.IsIndeterminate for the call chain.

Also check out my answer to this question: Centering the selected item in the scroll viewer

0
source

Source: https://habr.com/ru/post/985845/


All Articles