Search code examples
c#wpfsortingbooleancollectionviewsource

ICollectionView.SortDescriptions does not work for boolean


myListBox.Items.SortDescriptions.Add( new SortDescription("BoolProperty", ListSortDirection.Descending));

This sorting works only for string properties of the underlying project. Not with boolean? Is there a reason for that ?

Thanks !

UPDATE:

Yep, your example really works. But what's wrong on my example ?

public class A
{
    public bool Prop;            
}

List<A> l = new List<A>() {
    new A() { Prop = true  }, 
    new A() { Prop = false }, 
    new A() { Prop = true  },
};

ICollectionView icw = CollectionViewSource.GetDefaultView(l);                                                
icw.SortDescriptions.Add(new SortDescription("Prop", ListSortDirection.Ascending));                
icw.Refresh();

Solution

  • Hmm, I can seem to add a SortDescription on a boolean property in my list example!

    <Window x:Class="WpfApplication3.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
        <Grid>
            <ListBox x:Name="box" DisplayMemberPath="Test" />
        </Grid>
    </Window>
    

    Code behind:

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
    
            //4 instances, each with a property Test of another boolean value
            box.ItemsSource = new[] {
                new {Test = true}, 
                new {Test = false}, 
                new {Test = false}, 
                new {Test = true}
            };
    
            box.Items.SortDescriptions.Add(new SortDescription("Test", ListSortDirection.Descending));
        }
    }
    
    
    public class BooleanHolder
    {
        public bool Test { get; set; }
    }
    

    Works like a charm ;)

    Perhaps you misspelled the property name in the SortDescription object? Hope this helps

    In your example you defined Prop as a field. Make it a property and it will work ;)

    public class A
    {
        public bool Prop { get; set; }
    }