Search code examples
c#xamldata-bindingcollectionviewsource

CollectionViewSource Sorting Dynamically


I have a Car class with various properties.

I have a static Cars collection class in which, for simplicity, I have defined a bunch of car items which I can make available in XAML via an object data provider.

I have a collection view source defined in XAML which binds successfully to my ObjectDataProvider as it should.

I have a listbox which shows the collection.

I added the sort to the CVS as recommended in all the standard tutorials and all works fine.

My Question: Suppose I want to sort on a different field. Surely there is a way to change this without having to give the code to the customer. So I implemented a combo box.

I use the following code to load a list of properties from the Car class into the combo box but I don’t just get a list of properties. I also get their data types. I don’t want this.

Car xyz=new Car(); //Make a temp Car Object so we can get a list of properties.
//Assign this to the combobox for listing.
cbxSortPrimary.ItemsSource = xyz.GetType().GetProperties();

Result (what displays in the combo box):

System.String Model
Double Price
Int32 NoOfPrevOwners
DataType PropertyName
ect... ect...
ect... ect...
ect... ect...

My goal is to load in the property names to the combo box. Then use the selected property name to build a line of code like:

myListBox.Items.SortDescriptions.Add(new SortDescription(ComboBox.SelectedItem.ToString(), ListSortDirection.Descending));

Where the ComboBox.SelectedItem.ToString() will contain the name of the property to be sorted on.

So how do I get rid of the data type in front of the property name. I know I can do all sorts of messy loading into another list, then a bunch of string handling looking for the first space from the right and chopping everything before that. But surely there must be an easier way.

Effectively what I am looking to do is to let the user sort on a different property of the Car class (So I need to load the properties somewhere and make them available for the user to select, hence the combobox). What I am asking is that there must be an easy way to get the list of properties without all the string manipulation code, and hopefully without much reflection (unless I am already using it without knowing), as it seems like a very basic requirement.

Thanks in advance for any help!


Solution

  • It's not messy at all:

            var properties = new List<string>();
    
            foreach (var info in typeof(Car).GetProperties())
            {
                properties.Add(info.Name);
            }
            cbxSortPrimary.ItemsSource = properties;