1. C#
Teams teams = new Teams();
var result = from t in teams
group t by t.City into g
orderby g.Key
select new { Key = g.Key, Items = g };
groupInfoCVS.Source = result;
2. Layout
<Grid x:Name="root_layout" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="1">
<Grid>
<Grid.Resources>
<!-- IsSourceGrouped="true" ItemsPath="Items" -->
<CollectionViewSource x:Name="groupInfoCVS" IsSourceGrouped="true" ItemsPath="Items"/>
</Grid.Resources>
<ListView x:Name="lvGroupInfoCVS" ItemsSource="{Binding Source={StaticResource groupInfoCVS}}">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Key}" Foreground="BurlyWood" FontSize="30"/>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
<ListView.ItemTemplate>
<DataTemplate>
<Border Background="{Binding Color}" Width="200" CornerRadius="5" HorizontalAlignment="Left">
<TextBlock Text="{Binding Name}" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Center" FontWeight="Bold"/>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Grid>
3. Class
public class Team //Has a custom string indexer
{
Dictionary<string, object> _propBag;
public Team()
{
_propBag = new Dictionary<string, object>();
}
public string Name { get; set; }
public string City { get; set; }
public SolidColorBrush Color { get; set; }
// this is how you can create a custom indexer in c#
public object this[string indexer]
{
get
{
return _propBag[indexer];
}
set
{
_propBag[indexer] = value;
}
}
public void Insert(string key, object value)
{
_propBag.Add(key, value);
}
}
// This class is used to demonstrate grouping.
public class Teams : List<Team>
{
public Teams()
{
Add(new Team() { Name = "The Reds", City = "Liverpool", Color = new SolidColorBrush(Colors.Green) });// 0
Add(new Team() { Name = "The Red Devils", City = "Manchester", Color = new SolidColorBrush(Colors.Yellow) });// 1
Add(new Team() { Name = "The Blues", City = "London", Color = new SolidColorBrush(Colors.Orange) });// 2
Team _team = new Team() { Name = "The Gunners", City = "London", Color = new SolidColorBrush(Colors.Red) };
_team["Gaffer"] = "le Professeur";
_team["Skipper"] = "Mr Gooner";
Add(_team);// 3
}
}