WPF: Sort a list box
How do I sort a ListBox
by two fields? (In this case the ApplicationName
开发者_C百科 and InstanceName
properties of my model class.)
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));
}
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
精彩评论