5

I am trying to display a set of data using a DataTemplate in an ItemsControl, with the ItemsPanel set as a uniform grid of size 3 x 3. The ItemsSource of the ItemsControl is set to bind to a CollectionViewSource which filters the source collection based on a search term. This all works fine.

The list I am binding to is of an arbitrary size, but I only want 9 results to be displayed, but I can't for the life of me work out how to either:
a) limit the CollectionViewSource to output the first 9 items
b) limit the UniformPanel to only 3 x 3 and never to create new rows
c) limit the ItemsControl to only allow 9 data templates to be created at once.

I'm really scratching my head because I'm sure this is a common databinding scenario but I can't find anything on the web about it.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Guy
  • 3,353
  • 24
  • 28
  • Based on the answer of cwap, I have scrapped the CollectionViewSource entirely and just created a master list and a filtered list in the view model, the latter being updated when the search term changes. Using a converter is a good idea and probably more "pure" MVVM than including the maximum number of outputs in the VM (why I marked it as answer), but for now I'm happy with doing it in the VM. Cheers for the replies all. – Guy Dec 16 '09 at 14:20

3 Answers3

4

Two solutions I can think of:

If you are using View Model, put the logic in there to create a property that you can bind to that only ever has 9 elements. Make sure it's unit tested to ensure more than 9 elements never sneak into the collection.

Alternatively you could use a converter when binding the items source to convert the full list to a reduced list of the first 9.

James Hay
  • 12,580
  • 8
  • 44
  • 67
  • It is worth pointing out that the converter approach prevents change events propagating. If you add or remove from your bound data source it will not be reflected. – Andy Reed May 13 '14 at 20:45
2

This is just one of those things you can't do in XAML (yet).

You could create a "CollectionViewSourceView" (:P), which will be updated whenever CollectionViewSource is updated, to only output the first 9 items. Still, this is going into the codebehind (or better, the viewmodel).

cwap
  • 11,087
  • 8
  • 47
  • 61
1

I was about to say the same as James Hay (use a Converter), but I would also add that you can databind a ConverterParameter in the XAML to dynamically specify how many items are returned.

pete the pagan-gerbil
  • 3,136
  • 2
  • 28
  • 49