Welcome to today's edition of Steve's Programming Problems...
I have a listbox (lstSystems) bound to a collection of System objects (Galaxy.SystemList). The ToString for System has been overidden to return the System Name. Everything works fine and the listbox displays a list of system names. I would like to sort the systems alphabetically in the listbox. The Items property of the listbox has a collection of SortDescription objects, which is empty at runtime. Therefore I am using the following code snippet to try and sort the listbox on SystemName.
lstSystems.ItemsSource = Galaxy.SystemList;
lstSystems.Items.SortDescriptions.Add(new SortDescription("SystemName", ListSortDirection.Ascending));
The sort order does change after the second line is executed and it always changes in the same way, but it certainly isn't anything to do with system name. In fact, despite the fact the sort always happens in the same way I can find no rational explanation for the order of the systems. Any ideas? Am I missing something obvious?
EDIT: Another piece of the puzzle. If I change the ListSortDirection to Descending, I still get the same 'random' order as I do with Ascending!
EDIT2: If I change the second line of code to include a nonsense field name the program compiles and runs with no problem and I still get the same weird sort order. For some reason the fieldname is being ignored.
lstSystems.Items.SortDescriptions.Add(new SortDescription("TotallyRandomText", ListSortDirection.Ascending));
EDIT3: If I forget all of the above and sort the SystemList collection using the following (which I found but don't really understand), the listbox is sorted correctly (because the collection is sorted not the listbox view of the collection). I would still like to know why the original code doesn't work and why the new code does
SystemList.Sort
(delegate(StarSystem sys1, StarSystem sys2)
{
return Comparer<string>.Default.Compare
(sys1.SystemName, sys2.SystemName);
});
Steve