Hello!
I'm learning the ListView control and sorting data it shows, but i can't seem to fix a scenario.
I am using Visual Studio 2017 Community.
I am trying to have a list always ordered by this criteria:
- column create date (DateTime.Now)
- order descending
The following 3 scenarios must work with the same order criteria applied, but i can't seem to make it work for the 3rd one.
1) (working) When i open the app the 1st time (done with sorting in overriden Init method
2) (working) When i add items in the list (enter/done/verify on a specific Entry control adds to my ListView an item)
3) (not working) When, while the app is running , i navigate to another Page and back to the one that keeps this ListView
1) was solved with overriding Init method of the viewModel (which keeps the ObservableCollection prop)
2) was solved by using ObservableCollection.Insert(,item) instead of ObservableCollection.Add()
3) In the view, i tried overriding OnAppearing
In XAML:
<ListView
x:Name="ItemListView"
ItemsSource="{Binding Items}"
CachingStrategy="RecycleElement"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout
Spacing="10"
Orientation="Horizontal"
>
<StackLayout>
<Label
Text="{Binding Code}"
/>
<Label
Text="{Binding Description}"
/>
</StackLayout>
<Label
Text="{Binding Number}"
FontAttributes="Bold"
VerticalOptions="Center"
/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
In code-behind of View:
protected override async void OnAppearing()
{
base.OnAppearing();
await _itemViewModel.SaveItem(); //does some SQLite work related to Items
_itemPageViewModel.SortItems();
ItemListView.ItemsSource = _itemViewModel.Items;
}
In View-Model:
internal void SortItems()
{
Items.OrderByDescending(x => x.CreateDate);
}
However, when i repeatedly exit the Page and reenter, the items are unsorted.