How do I apply custom sorting to the order of the items in a bound listbox?

Platform: WPF| Category: DataBinding

To specify custom sorting using a custom implementation of an IComparer, you will have to use a CollectionViewSource, get it’s default view and set it’s CustomSort property as follows:

Sample ListBox bound to a CollectionViewSource:


<Window x:Class='WindowsApplication1.Window1'
    xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
    xmlns:scm='clr-namespace:System.ComponentModel;assembly=windowsbase'
>
  <Window.Resources>
    <XmlDataProvider x:Key='list' >
      <x:XData>
        <Items xmlns=''>
          <Item>
            <Name>David</Name>
            <Age>20</Age>
          </Item>
          <Item>
            <Name>Marcus</Name>
            <Age>25</Age>
          </Item>
          <Item>
            <Name>George</Name>
            <Age>25</Age>
          </Item>
          <Item>
            <Name><![CDATA[Peter&#M]]></Name>
            <Age>25</Age>
          </Item>
        </Items>
      </x:XData>
    </XmlDataProvider>
    <CollectionViewSource
        Source='{Binding Source={StaticResource list}, XPath=Items/Item/Name}'
        x:Key='data'/>
  </Window.Resources>
  <ListBox
      Name='lb1'
      DisplayMemberPath='Name'
      ItemsSource='{Binding Source={StaticResource data}}'/>
</Window>

Then in code-behind specify the custom comparer as follows:


public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        this.lb1.Loaded += delegate
        {
            CollectionViewSource cvs = this.TryFindResource('data') as CollectionViewSource;
            if (cvs != null)
            {
                ListCollectionView view = cvs.View as ListCollectionView;
                if (view != null)
                {
                    view.CustomSort = new XmlComparer();
                }
            }
        };
    }

    public class XmlComparer : IComparer
    {
        public Int32 Compare(Object x, Object y)
        {
            XmlElement a = x as XmlElement;
            XmlElement b = y as XmlElement;
            if (a != null && b != null)
            {
                return String.Compare(a.InnerText, b.InnerText);
            }

            return -1;
        }
    }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.