Bind listbox in WPF with grouping

Posted by Michael Stoll on Stack Overflow See other posts from Stack Overflow or by Michael Stoll
Published on 2010-04-07T20:26:51Z Indexed on 2010/04/08 7:53 UTC
Read the original article Hit count: 431

Filed under:
|
|
|

Hi,

I've got a collection of ViewModels and want to bind a ListBox to them. Doing some investigation I found this.

So my ViewModel look like this (Pseudo Code)

interface IItemViewModel 
{
 string DisplayName { get; }
}

class AViewModel : IItemViewModel 
{
 string DisplayName { return "foo"; }
}

class BViewModel : IItemViewModel 
{
 string DisplayName { return "foo"; } 
}

class ParentViewModel 
{
 IEnumerable<IItemViewModel> Items 
 {
  get
  {
   return new IItemViewModel[] {
    new AItemViewModel(),
    new BItemViewModel()
   }
  }
 }
}

class GroupViewModel 
{
 static readonly GroupViewModel GroupA = new GroupViewModel(0);
 static readonly GroupViewModel GroupB = new GroupViewModel(1);

 int GroupIndex;
 GroupViewModel(int groupIndex) 
 {
  this.GroupIndex = groupIndex;
 }

 string DisplayName
 {
  get { return "This is group " + GroupIndex.ToString(); }
 }
}

class ItemGroupTypeConverter : IValueConverter
{
 object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
  if (value is AItemViewModel)
   return GroupViewModel.GroupA;
  else 
   return GroupViewModel.GroupB;
 }
}

And this XAML

<UserControl.Resources>
 <vm:ItemsGroupTypeConverter x:Key="ItemsGroupTypeConverter "/>
 <CollectionViewSource x:Key="GroupedItems" Source="{Binding Items}">
  <CollectionViewSource.GroupDescriptions>
   <PropertyGroupDescription Converter="{StaticResource ItemsGroupTypeConverter }"/>
  </CollectionViewSource.GroupDescriptions>
 </CollectionViewSource>
</UserControl.Resources>
<ListBox ItemsSource="{Binding Source={StaticResource GroupedItems}}">
 <ListBox.GroupStyle>
  <GroupStyle>
   <GroupStyle.HeaderTemplate>
    <DataTemplate>
     <TextBlock Text="{Binding DisplayName}" FontWeight="bold" />
    </DataTemplate>
   </GroupStyle.HeaderTemplate>
  </GroupStyle>              
 </ListBox.GroupStyle>
 <ListBox.ItemTemplate>
  <DataTemplate>
   <TextBlock Text="{Binding DisplayName}" />
  </DataTemplate>
 </ListBox.ItemTemplate>
</ListBox>

This works somehow, exept of the fact that the binding of the HeaderTemplate does not work. Anyhow I'd prefer omitting the TypeConverter and the CollectionViewSource. Isn't there a way to use a property of the ViewModel for Grouping?

I know that in this sample scenario it would be easy to replace the GroupViewModel with a string an have it working, but that's not an option. So how can I bind the HeaderTemplate to the GroupViewModel?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about listbox