解決方案的fundementals在使用另一種ItemsControl
ListBox
的ItemTemplate
。這ItemsControl
應該有一個水平面向StackPanel
作爲其ItemsPanel
。
這裏是一個基本的例子。讓我們先從一些很簡單的TESTDATA: -
public class TestStringList : List<string>
{
public TestStringList()
{
AddRange(new[] {"Anthony", "Kar", "Martin", "Jon", "Erik", "Darin",
"Balus", "Mike", "Hans", "Alex", "Anomie", "David" });
}
}
現在,我們希望在一個列表框來顯示這個列表,但保留所有具有在同一行同一首字母的名字。我將使用IValueConverter
的實現來處理我們需要的分組。如果您使用的是MVVM,那麼您可以使用ViewModel。
public class Grouper : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((IEnumerable<string>)value).OrderBy(s => s).GroupBy(s => s[0]);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
該轉換器的輸出基本上是IEnumerable<IEnumerable<string>>
這就是我們想要的。外部列表框將枚舉外部集合,並且內部ItemsControl
將枚舉內部集合的字符串,這將是具有相同初始值的一組名稱。
這裏是XAML: -
<UserControl x:Class="SilverlightApplication1.SimpleGrouping"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SilverlightApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
<local:TestStringList x:Key="TestData" />
<local:Grouper x:Key="grouper" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<ListBox ItemsSource="{Binding Converter={StaticResource grouper}, Source={StaticResource TestData}}">
<ListBox.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" Margin="5" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
真的很好:)。投票! – TCM 2011-03-24 18:03:01