So I have a ListView
control backed by an ObservableCollection<>
which periodically gets items added to it. However I would only like to display at most the first 10 items; ie if there are at most 10 items it displays them all, while resizing accordingly, and if there are more than 10 it stops displaying them at the 10th item.
I was wondering if there was a reasonable way to do this as my current intuition is to have a second collection which mirrors the top 10 items of the ItemsSource, updating accordingly.
You could do something like this (i haven't tested it, but you may get the idea):
_defaultView = CollectionViewSource.GetDefaultView(YourCollection);
_defaultView.SortDescriptions.Add(new System.ComponentModel.SortDescription(".", System.ComponentModel.ListSortDirection.Ascending));
_defaultView.Filter = o =>
{
int index = YourCollection.OrderBy(s => s).ToList().IndexOf(o as string);
return index >= 0 && index < 10;
};
_defaultView.Refresh();
I prefer using a converter for this rather than adding new model value or other extra collections as that often interferes with the change tracking.
The following filter sets the list to a fixed size of 10:
<ItemsControl ItemsSource="{Binding Configuration.RecentDocuments,Converter={StaticResource ItemSourceCountFilterConverter},ConverterParameter=10}"
This converter basically takes the original IEnumerable and filters it down to the desired count of items and returns it:
public class ItemSourceCountFilterConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var val = value as IEnumerable;
if (val == null)
return value;
int take = 10;
if (parameter != null)
int.TryParse(parameter as string, out take);
if (take < 1)
return value;
var list = new List<object>();
int count = 0;
foreach (var li in val)
{
count++;
if(count > take)
break;
list.Add(li);
}
return list;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.