WPF: Sort a list box

2019-04-12 18:07发布

问题:

How do I sort a ListBox by two fields? (In this case the ApplicationName and InstanceName properties of my model class.)

回答1:

It depends on your data source. Here are a couple of ways....

using linq on lisbox data source

from 101 LINQ Samples:

string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var sortedDigits =
        from d in digits
        orderby d.Length, d
        select d;

use a CollectionView for your listbox and add a SortDescription

ICollectionView myDataView = CollectionViewSource.GetDefaultView(myData);

using (myDataView.DeferRefresh()) // we use the DeferRefresh so that we refresh only once
{
   myDataView.SortDescriptions.Clear();
   if (SortById)
      myDataView.SortDescriptions.Add(new SortDescription("ApplicationName", direction));
   if (SortByName)
         myDataView.SortDescriptions.Add(new SortDescription("InstanceName", direction));
}


回答2:

you can try to add both fields into the listbox items SortDescriptions collection, smth like this:

listBox1.Items.SortDescriptions.Add(new SortDescription("ApplicatonName", ListSortDirection.Descending));
listBox1.Items.SortDescriptions.Add(new SortDescription("InstanceName", ListSortDirection.Descending));

above code should sort the listbox items in the descending order by fileds ApplicatonName and InstanceName

hope this helps, regards