I have a ListBox which ItemSource is bound to a CollectionViewSource
. The CVS Source is an XmlDataProvider
. So the ListBox lists all nodes (name attrib
If you are binding to a collection that inherits from IList, you can retrieve a ListCollectionView from the ItemsSource property of your ListView control. Once you have an instance of a ListCollectionView, you can assign a sorting method to the CustomSorter property.
The custom sorter must inherit from the old style, non-generic IComparer. Within the Compare method, you get two instances of the bound class. You can cast those as needed to get your desired result. During development, you can anchor the debugger inside the Compare method to determine exactly what the objects are.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List strings = new List() { "3", "2", "10", "1" };
lv1.ItemsSource = strings;
ListCollectionView lcv =
CollectionViewSource.GetDefaultView(lv1.ItemsSource) as ListCollectionView;
if(lcv!=null)
{
lcv.CustomSort = new MySorter();
}
}
}
public class MySorter : IComparer
{
public int Compare(object x, object y)
{ // set break point here!
return Convert.ToInt32(x) - Convert.ToInt32(y);
}
}