WPF: Bind Collection with Collection to a ListBox with groups

前端 未结 2 829
轮回少年
轮回少年 2021-02-04 16:37

sometimes WPF is too complex for me. I\'ve got my \"Window1\" holding a collection of \"Group\"s. \"Group\" is a class with a collection of \"Person\"s. In the end this should b

2条回答
  •  情话喂你
    2021-02-04 17:06

    If you have a copy of Programming WPF, jump to Page 221. If not I'll summarize (in my inept sort of way)

    First you don't need to manually group the Person objects.

    If each Person object has a Group property,

    People people = // retrieve the List somehow
    ICollectionView view = CollectionViewSource.GetDefaultView(people);
    view.GroupDescriptions.Add( new PropertyGroupDescription("Group") );
    

    All controls that derive from ItemsControl can display grouped items, so

    // the XAML
    
      
        
      
    
    

    You can also define a custom GroupStyle and specify the GroupStyle.HeaderTemplate to define a new DataTemplate that shows custom attributes like 'some PropertyValue (Count)' - Bind the one TextBlock to {Binding SomeProperty} and the other to {Binding ItemCount}

    HTH

提交回复
热议问题