Listview Grouping - IsGroupingEnabled

DavidWeDavidWe Member ✭✭

My question is simple:

Which steps do i have to do to activate and deactivate the grouping from a listview at runtime? IsGroupingEnabled = false

I have a perfect grouped Listview with its Itemsource bound to an observable collection of a groupviewmodel.

But the moment i decide to deactivate the property 'IsGroupingEnabled', i see a blank list without any functional template.
Every binding seems to be gone and the list presents itself with a list and each item.tostring();

I already found out out that i definatley have to remove the Listview.GroupHeaderTemplate = null
otherwise it still exists.

Interesting fact, if i set IsGroupingEnabled to 'false' before the listview is generated the firsttime the same datatemplate works for me...

Or do i have to use a second listview, beause it will never get rid of the template cache ?

Posts

  • JoeMankeJoeManke USMember ✭✭✭✭✭
    edited May 2018

    A ListView with grouping requires an ItemsSource that is a list of lists. The GroupHeaderTemplate binds to properties of the top level item, and the ItemTemplate binds to the second-level items.

    So let's say this is your very simple model:

    public class Item
    {
        public string ItemName { get; set; }
    }
    
    public class ItemGroup : IEnumerable<Item>
    {
        public string GroupName { get; set; }
    
        public ObservableCollection<Item> Items { get; set; }
    
        public IEnumerator<Item> GetEnumerator()
        {
            return Items.GetEnumerator();
        }
    }
    
    public class ViewModel
    {
        public ObservableCollection<ItemGroup> GroupedItems { get; set; }
    }
    

    Then you bind your ListView's ItemsSource to GroupedItems.

    When you set IsGroupingEnabled false, what do you want the ListView to show?

    1. The ItemGroup objects, without the child Item objects: Change the ItemTemplate to the DataTemplate you were previously using as the GroupHeaderTemplate
    2. The Item objects, without being grouped under ItemGroup objects: Change the ItemsSource to an IEnumerable<Item> of some sort. A very simple way to get this from your grouped collection is GroupedItems.SelectMany(x => x).ToList() which will return a List<Item>.
  • DavidWeDavidWe Member ✭✭

    Thanks so much for the answer.
    It never occured to me to basically morph the groupheadertemplate into my target template after i switch the setting.

    But i also did a crucial mistake, since my bound property 'IsGroupingEnabled' never raised an OnPropertyChanged event.
    I thought it wasn't simply neccessary since i always recreated my datasource (an observable collection).
    And now i had the correct template but the bound properties never refreshed themselves...

Sign In or Register to comment.