I have a TabbedPage
and it contains a few ContentPage
that are consisting of a ContentView
and some of them has a ListView
.
The ListView
contains a grouped ItemsSource
represented by a custom model class:
public class DataGroup: List<DataGroupItem>
{
public string HeaderText { get; set; }
public string ShortName { get; set; }
public string SubTitle { get; set; }
public DataGroup(string headerText, string shortName)
{
HeaderText= headerText;
ShortName= shortName;
}
}
The XAML code (it has an ItemTemplate as well):
<ListView x:Name="listView"
Grid.Row="0"
GroupDisplayBinding="{Binding HeaderText}"
GroupShortNameBinding="{Binding ShortName}"
HasUnevenRows="True"
IsGroupingEnabled="True"
ItemsSource="{Binding DataGroups}"
SeparatorColor="Black"
SeparatorVisibility="Default">
...
</ListView>
When I change the actual tab, I need the ListView
to be scrolled to a certain group.
I use this code:
ObservableCollection<DataGroup> dataGroups
= this.listView.ItemsSource as ObservableCollection<DataGroup>;
if (scrolling)
{
var res = dataGroups.Where(dg=>dg.ItemCount > 3).LastOrDefault();
if (res != null)
//Device.StartTimer(TimeSpan.FromMilliseconds(150), () =>
//{
this.listView.ScrollTo(res, ScrollToPosition.Center, false);
//return false;
//});
}
I tried all variations in ScrollToPosition
, unfortunately, nothing happens.
What else should I try?
Well, it was quite an adventure to figure this out.
First, I thought I should set a child item as the target of the ScrollTo
method, but it changed nothing.
As a vague idea, I added the SelectedItem
into the soup, and it worked, so I have this as a final result:
ObservableCollection<DataGroup> dataGroups= this.listView.ItemsSource as ObservableCollection<DataGroup>;
if (scrolling)
{
var res = dataGroups.Where(dg=>dg.ItemCount > 3).LastOrDefault();
if (res != null && res.Count > 0)
{
this.listView.SelectedItem = res[0];
this.listView.ScrollTo(this.listView.SelectedItem, ScrollToPosition.MakeVisible, false);
}
}
Don't forget to set also the group. You need to set both the group and the item, see example below:
listView.ScrollTo(item, group, ScrollToPosition.Start, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With