WPF ListView grouping by 2 columns but display only 1 group header

前端 未结 2 1884
清酒与你
清酒与你 2021-01-07 01:28

A ListView displays a collection of the following class:

public class Employee
{
    private string _department;
    private string _manager;
    private str         


        
2条回答
  •  逝去的感伤
    2021-01-07 02:16

    I would create another model part, which represents the dual grouping that you need to have happen:

    Model Classes:

    public class EmployeeModel {
    
            private readonly Employee _Employee;
    
            public DepartmentManager ManagementInfo { get; private set; }
    
            public string Name {
                get { return _Employee.Name; }
            }
            public string Address {
                get { return _Employee.Address; }
            }
    
            public EmployeeModel(Employee employee) {
                this._Employee = employee;
                this.ManagementInfo = new DepartmentManager(employee.Department, employee.Manager);
            }
        }
    
        public class DepartmentManager {
    
            public string Department { get; private set; }
            public string Manager { get; private set; }
    
            public DepartmentManager(string dept, string manager) {
                this.Department = dept;
                this.Manager= manager;
            }
    
            public override bool Equals(object obj) {
                var model = obj as DepartmentManager;
                if(null == model)
                    return false;
    
                return Department.Equals(model.Department, StringComparison.InvariantCultureIgnoreCase) && 
                    Manager.Equals(model.Manager, StringComparison.InvariantCultureIgnoreCase);
            }
        }
    

    XAML:

        
            
                
            
        
    
        
            
                
                
            
        
    
    ...
        
                
                    
                        
                            
                                
                                    
                                    
                                
                            
                        
                    
                
            
    

    Then in your Window/ViewModel:

    this.EmployeesModel = new ObservableCollection(MyListOfEmployersFromDB.Select(e => new EmployeeModel(e)));
    

    Note, I've overriden Equals in the DepartmentManager class, but not GetHashCode, ideally you should do a custom implementation of that. I had to override equals so the grouping view source would correctly group the same entries. You could get rid of this need, buy constructing the DepartmentManager for the same Employees outside of the collection, and pass them into the EmployeeModel ctr.

提交回复
热议问题