Numerical string sorting in a listbox

后端 未结 1 1773
执笔经年
执笔经年 2021-01-24 09:57

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

1条回答
  •  鱼传尺愫
    2021-01-24 10:23

    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);
        }
    }
    

    0 讨论(0)
提交回复
热议问题