WPF: Sort a list box

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-01 18:30:28

问题


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



来源:https://stackoverflow.com/questions/2136827/wpf-sort-a-list-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!