WPF 如何设置 CollectionViewSource 结果的最大数量
我正在尝试使用 ItemsControl
中的 DataTemplate
显示一组数据,并将 ItemsPanel
设置为大小为 3 x 3 的统一网格ItemsControl
的 ItemsSource
设置为绑定到 CollectionViewSource
,后者根据搜索词过滤源集合。这一切都很好。
我绑定的列表是任意大小的,但我只想显示 9 个结果,但我一生都无法弄清楚如何:
a) 限制 CollectionViewSource
输出前 9 项
b) 将 UniformPanel
限制为仅 3 x 3 并且从不创建新行
c) 将 ItemsControl
限制为仅允许一次创建 9 个数据模板。
我真的很摸不着头脑,因为我确信这是一个常见的数据绑定场景,但我在网上找不到任何关于它的信息。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这只是 XAML 中(目前)还不能做的事情之一。
您可以创建一个“CollectionViewSourceView”(:P),每当 CollectionViewSource 更新时,该视图都会更新,以仅输出前 9 项。尽管如此,这仍然会进入代码隐藏(或者更好的是视图模型)。
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).
我本来想说的是与 James Hay 相同的内容(使用转换器),但我还要补充一点,您可以在 XAML 中对 ConverterParameter 进行数据绑定,以动态指定返回的项目数。
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.
我能想到的两个解决方案:
如果您使用视图模型,请将逻辑放在那里来创建一个可以绑定到只有 9 个元素的属性。确保对其进行单元测试,以确保集合中不会出现超过 9 个元素。
或者,您可以在将项目源绑定到时使用转换器将完整列表转换为前 9 个的精简列表。
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.