Sort ListView items?

I have a ListView that contains four columns in which I add items dynamically:

ListViewItem lvi = new ListViewItem();
lvi.Background = ... color you want ... ;
lvi.Content = new {Server = "test1", .... };
listViewResult.Items.Add(lvi);

Now I want to sort this dynamically generated ListView when I click on a column column. How can I achieve this?

+3
source share
1 answer

I found an article here that explains custom sorting.

VirtualizingStackPanel.IsVirtualizing="True"

First you need to specify the above property to true in your ListView, (this is the default value for ListView in WPF).

Then next, you need to use custom sorter, instead of SortDescriptions as described in my earlier blog. The key is using the CustomSort property of ListCollectionView:
ListCollectionView view = (ListCollectionView)CollectionViewSource.GetDefaultView(myListView.ItemsSource);

Then in your ColumnHeader click event handler, you add something like the following:

view.CustomSort = sorter;
myListView.Items.Refresh();

Where sorter is a custom class you implement the IComparer interface.
0
source

Source: https://habr.com/ru/post/1789192/


All Articles