WPF How to set a maximum amount of results from CollectionViewSource

时光怂恿深爱的人放手 提交于 2020-02-03 07:29:29

问题


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.


回答1:


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.




回答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).




回答3:


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.



来源:https://stackoverflow.com/questions/1914786/wpf-how-to-set-a-maximum-amount-of-results-from-collectionviewsource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!