I'am currently developing an WinRT app an need a ListView ordered by date and grouped by day. The ListView is bound to an ICollectionView in my ViewModel
public Windows.UI.Xaml.Data.ICollectionView GroupedData {
get
{
return cvSource.View;
}
}
private Windows.UI.Xaml.Data.CollectionViewSource cvSource;
In my XAML I can bind then the ListView to this property:
<ListView ItemsSource="{Binding GroupedData}"
Now I'am doing some calculations and Filtering on my basicData, which is stored in a List<>. After i've done this, the grouping happens via LINQ:
var result = from DataObject in basicData
group DataObject by DataObject.Date
into date_grp orderby date_grp.Key
select date_grp;
Finally I set the source of the CollectionView to this new result and fire OnPropertyChanged
cvSource.Source = result.ToList();
OnPropertyChanged("GroupdedData");
This is working as I expected, but the ListView now selects the first element every time I populate a new source. I got rid of this as described on Stackoverflow by sellmeadog
NowI like to manually select an item. This should be the previous selected item before the source of the CollectionView is changed. What is the best way to save this previous item, see if its in the newly created CollectionView, select it and scroll to it?
Best regards
For the selecting senario, add a new property to the ViewModel in and bind SelectedItem property of the ListView to it:
public Windows.UI.Xaml.Data.ICollectionView GroupedData {
get
{
return cvSource.View;
}
}
public YourObjectType CurrentItem {
get {
return this.currentItem;
}
set {
if (this.currentItem != value) {
this.currentItem = value;
this.OnPropertyChanged("CurrentItem");
}
}
}
private YourObjectType currentItem;
private Windows.UI.Xaml.Data.CollectionViewSource cvSource;
Then before setting the source, hold a reference to the current item
var current = this.CurrentItem;
cvSource.Source = result.ToList();
this.CurrentItem = current;
assuming that your DataObjects type overrides Equals method, ListView finds and selects it in the collection. If not, you may need to add code finding it's instance in the new collection and assign it to CurrentItem property.
But by selecting the item doesn't mean ListViewScrolls to it. You may need to call ListView.BringIntoView in order to scroll to the selected item.