So finally, I get the ViewportControl that I've been looking for the LongListSelector from so long but when I try to scroll to a specific offset using the below methods, I'm not able to scroll to the offset.
I'm using a public static class GlobalVars
(Global Variables) to pass data between pages.
So when a user selects an item
from the LongListSelector -> Navigates to ItemDetail Page by this:
private void llsArtists_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
GetFirstVisibleItem(llsArtists);
var artist = (Artist)e.AddedItems[0];
GlobalVars._artistName = artist.ArtistName;
GetSelectedArtist(artist.ArtistName);
NavigationService.Navigate(new Uri("/ArtistDetail.xaml", UriKind.Relative));
}
and then comes back to the same page by hitting Back
Key, I would like the user to be on the same item as the last one (currently it jumps to the first index.) Therefore, I get the Viewport and the vertical offset:
private void GetFirstVisibleItem(LongListSelector lls)
{
var offset = FindViewport(lls).Viewport.Top;
GlobalVars._artistScrollOffset = offset;
}
private static ViewportControl FindViewport(DependencyObject parent)
{
var childCount = VisualTreeHelper.GetChildrenCount(parent);
for (var i = 0; i < childCount; i++)
{
var elt = VisualTreeHelper.GetChild(parent, i);
if (elt is ViewportControl)
return (ViewportControl)elt;
var result = FindViewport(elt);
if (result != null)
return result;
}
return null;
}
and finally ScrollToOffset
void ScrollToOffset()
{
Point loc = new Point();
loc.X = 0;
//loc.Y = Math.Round(GlobalVars._artistScrollOffset, 2);
loc.Y = GlobalVars._artistScrollOffset;
FindViewport(llsArtists).SetViewportOrigin(loc);
}
The problem is - If I explicitly set the value of Y for the Point
loc like I set the loc.X = 0
, it just works fine! The LongListSelector works perfectly! But, if I would like it to be a variable which is exactly what I would like it to be - IT JUST DOESN'T WORK! I find this very strange? What could be causing this? Any help would be appreciated!