我正在尝试确定是否有一种方法可以使用ItemsControl将ItemsSource中的项目分组到各个ItemsPanel中。具体来说,我试图创建一个视图,这样一个由8个项目组成的集合可以以网格类型的方式列出,就像UniformGrid一样,但结果是均匀的,而不是空单元格。
而源中有8个项目的UniformGrid会产生如下结果:
-------------------------------------
- +++++++++ - +++++++++ - +++++++++ -
-------------------------------------
- +++++++++ - +++++++++ - +++++++++ -
-------------------------------------
- +++++++++ - +++++++++ - ooooooooo -
-------------------------------------
(最后一个单元格为空)
我正试图产生这样的结果:
-------------------------------------
- +++++++++ - +++++++++ - +++++++++ -
-------------------------------------
- +++++++++ - +++++++++ - +++++++++ -
-------------------------------------
- +++++++++++++++ - +++++++++++++++ -
-------------------------------------
如果我以编程方式将其分解,我可以通过如下嵌套轻松地获得显示:
<StackPanel Orientation="Horizontal">
<UniformGrid>
item 1
item 2
item 3
</UniformGrid>
<UniformGrid>
item 4
item 5
item 6
</UniformGrid>
<UniformGrid>
item 7
item 8
</UniformGrid>
</StackPanel>
但我想通过Xaml获得我想要的结果。
我找到了一种方法,在绑定到集合的DataTemplate中嵌套一个新的ItemsControl,并使用ValueConverter将集合转换为数组数组。
<ItemsControl ItemsSource="{Binding MyCollection, Converter={StaticResource ArraySplitConverter}, ConverterParameter=3}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Title} />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
和ValueConverter:
public class ArraySplitConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int param = System.Convert.ToInt16(parameter);
object[] coll = (object[])value;
ArrayList outer = new ArrayList();
ArrayList inner = new ArrayList();
for (int i = 0; i < coll.Length; i++)
{
inner.Add(coll[i]);
if (((i + 1) % param == 0) || (i == coll.Length - 1)) { outer.Add(inner); inner = new ArrayList(); }
}
return outer;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}