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