我有一个列表框,它绑定到一个简单对象的列表。正如我们所知,默认情况下列表框将其项目托管为 Stackpanel,因此它以这种方式布置项目
item1
item2
item3
item4
item5
item6
但是我有一些条件,通过这些条件我检查项目是水平还是垂直显示,因此可以布置项目以这种方式
例如:-
item1
item2
item3 item4 item 5
item6
怎么可能做到这一点?
(如果你想知道为什么我需要这样的东西,一个示例场景是“facebook 风格更新”,其中如果用户连续上传 3-4 张照片,它们并不总是出现在下一行,但它可能会水平显示,而如果他发布一些事件,它会出现在下一行。)
提前致谢:)
I have a listbox and it's bound to a list of simple objects. As we know the listbox by default has it's items host as a Stackpanel and so it lays out items in this fashion
item1
item2
item3
item4
item5
item6
However i have some conditions through which i check whether the item is to be displayed horizontally or vertically and therefore the items could be laid out in this fashion
Eg :-
item1
item2
item3 item4 item 5
item6
How is it possible to do this?
(If you are wondering why would i ever need such a thing, an example scenario would be "facebook style updates" where if a user uploads 3-4 photos continously they don't always appear on the next line but it may appear horizontally whereas if he posts some event it appears in next line.)
Thanks in advance :)
发布评论
评论(2)
如果使用 MVVM 模式 我会做这样的事情:
ListItemViewModel
实例的集合(请参阅下一点)您的视图看起来像这样,每个视图都有一个相应的 ViewModel。
就像我上面说的,你肯定会想要更改视图/视图模型的名称,我的用于演示目的仅有的 :)
If using the MVVM pattern I would do something like this:
ListItemViewModel
instances (see next point)Your view would look something like this, each with a correspoding ViewModel.
Like I said above, you'll definitely want to change the name of your views/view models, mine are for demonstration purposes only :)
该解决方案的基本原理是在
ListBox
的ItemTemplate
中使用另一个ItemsControl
。此ItemsControl
应具有水平方向的StackPanel
作为其ItemsPanel
。这是一个基本示例。让我们从一些非常简单的测试数据开始:-
现在我们想要在列表框中显示此列表,但将具有相同首字母缩写的所有名称保留在同一行。我将使用
IValueConverter
的实现来处理我们需要的分组。如果您使用 MVVM,那么您的 ViewModel 就会接受这一点。该转换器的输出基本上是
IEnumerable>
这就是我们想要的。外部 ListBox 将枚举外部集合,内部ItemsControl
将枚举内部字符串集,这些字符串将是一组具有相同首字母的名称。这是 xaml:-
The fundementals of the solution is to use another
ItemsControl
in theItemTemplate
of theListBox
. ThisItemsControl
should have a horizontal orientedStackPanel
as itsItemsPanel
.Here is a basic example. Lets start with some very simple testdata:-
Now we want to display this list in a ListBox but keep all the names that have the same first initial on the same line. I'm going to use an implementation of
IValueConverter
to deal with the grouping that we need. If you are using MVVM then you'd have your ViewModel take of this.The output of this converter is basically
IEnumerable<IEnumerable<string>>
which is what we want. The outer ListBox will enumerate the outer set and the innerItemsControl
will enumerate the inner set of strings which will be a set of names with the same initial.Here is the xaml:-