|
1 | 1 | # xamarin-forms-listview-custom-sorting
|
2 | 2 | Xamarin Forms ListView provides support to custom sort the items using Comparer.
|
| 3 | + |
| 4 | +## Sample |
| 5 | + |
| 6 | +```xaml |
| 7 | +<sync:SfListView x:Name="listView" |
| 8 | + ItemSize="70" |
| 9 | + FocusBorderThickness="0" |
| 10 | + SelectionBackgroundColor="#ECECEC" IsScrollBarVisible="False" |
| 11 | + ItemsSource="{Binding ContactsInfo}"> |
| 12 | + |
| 13 | + <sync:SfListView.DataSource> |
| 14 | + <dataSource:DataSource> |
| 15 | + <dataSource:DataSource.SortDescriptors> |
| 16 | + <dataSource:SortDescriptor> |
| 17 | + <dataSource:SortDescriptor.Comparer> |
| 18 | + <local:CustomSortComparer/> |
| 19 | + </dataSource:SortDescriptor.Comparer> |
| 20 | + </dataSource:SortDescriptor> |
| 21 | + </dataSource:DataSource.SortDescriptors> |
| 22 | + </dataSource:DataSource> |
| 23 | + </sync:SfListView.DataSource> |
| 24 | + |
| 25 | + <sync:SfListView.ItemTemplate> |
| 26 | + <DataTemplate> |
| 27 | + <ViewCell> |
| 28 | + <ViewCell.View> |
| 29 | + <code> |
| 30 | + . . . |
| 31 | + . . . |
| 32 | + <code> |
| 33 | + </ViewCell.View> |
| 34 | + </ViewCell> |
| 35 | + </DataTemplate> |
| 36 | + </sync:SfListView.ItemTemplate> |
| 37 | +</sync:SfListView> |
| 38 | + |
| 39 | +CustomSortComparer: |
| 40 | +public class CustomSortComparer : IComparer<object> |
| 41 | +{ |
| 42 | + public int Compare(object x, object y) |
| 43 | + { |
| 44 | + if (x.GetType() == typeof(ListViewContactsInfo)) |
| 45 | + { |
| 46 | + var xitem = (x as ListViewContactsInfo).ContactName; |
| 47 | + var yitem = (y as ListViewContactsInfo).ContactName; |
| 48 | + |
| 49 | + if (xitem.Length > yitem.Length) |
| 50 | + { |
| 51 | + return 1; |
| 52 | + } |
| 53 | + else if (xitem.Length < yitem.Length) |
| 54 | + { |
| 55 | + return -1; |
| 56 | + } |
| 57 | + else |
| 58 | + { |
| 59 | + if (string.Compare(xitem, yitem) == -1) |
| 60 | + return -1; |
| 61 | + else if (string.Compare(xitem, yitem) == 1) |
| 62 | + return 1; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + return 0; |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
0 commit comments