Sort a wpf datagrid programmatically

前端 未结 6 2403
攒了一身酷
攒了一身酷 2020-11-29 08:22

Is there a way to sort a WPF DataGrid programmaticaly ( for example, like if i clicked on my first column).

Is there a way to simuate this click ? Or a best way ?

6条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 08:48

    you can use ICollectionView to filter, sort and group your items in a datagrid.

    EDIT: add Sort, did not read the question carefully :)

     var view = CollectionViewSource.GetDefaultView(this.MyData);
     view.Filter = ViewFilter;
     view.SortDescriptions.Add(new SortDescription("MyPropertyToSort", ListSortDirection.Descending));
    
    
        private bool ViewFilter(object obj)
        {
            var item = obj as MyObject;
    
            if (item == null)
                return false;
    
            //your filter logik goes here
    
            if(item.MyStringProp.StartsWith("Test"))
                return false;
    
            return true;
    
    
       }
    

提交回复
热议问题