How do you sort a CollectionViewSource by one property, then by another as a tiebreak?

后端 未结 3 1836
北海茫月
北海茫月 2021-01-07 22:35

Currently, my CollectionViewSource sorts a collection of items by description. If the description is the same, I want to sort based on ID. How can I specify to sort by descr

3条回答
  •  不知归路
    2021-01-07 23:03

    I'm not sure why adding the SortDescription for Id does not work as it should work fine.

    Like this:

    
        
            
            
        
     
    

    I put together a full example of this working as you want:

    Xaml:

    
    
    
       
        
            
            
        
       
    
    
    
        
    
    

    Code:

    public partial class MainWindow : Window
    {
        private ObservableCollection myVar = new ObservableCollection();
    
        public MainWindow()
        { 
            InitializeComponent();
            Items.Add(new MyObject { Description = "Stack", Id = 5 });
            Items.Add(new MyObject { Description = "OverFlow", Id = 1 });
            Items.Add(new MyObject { Description = "StackOverFlow", Id = 2 });
            Items.Add(new MyObject { Description = "Stack", Id = 1 });
            Items.Add(new MyObject { Description = "Stack", Id = 0 });
            Items.Add(new MyObject { Description = "OverFlow", Id = 7 });  
        }
    
        public ObservableCollection Items
        {
            get { return myVar; }
            set { myVar = value; }
        }
    }
    
    
    public class MyObject
    {
        public int Id { get; set; }
        public string Description { get; set; }
    
        public override string ToString()
        {
            return string.Format("Desc: {0}, Id: {1}", Description, Id);
        }
    }
    

    Result:

    enter image description here

提交回复
热议问题