简体   繁体   中英

WPF ComboBox with entity framework orderBy

I filled the ComboBox in my Project like this

            CB_City.ItemsSource = c.Cities;
            CB_City.DisplayMemberPath = "city1";
            CB_City.SelectedValuePath = "city_id";
            CB_City.SelectedValue = 517;

I work with entity Framework and c# , How can I sort the results in order by ascending?

Still can not (I'm trying a lot) I am attaching the full code

           using (MorEntities1  c = new MorEntities1())
        {
            CB_City.ItemsSource = c.Cities;
            CB_City.DisplayMemberPath = "city1";
            CB_City.SelectedValuePath = "city_id";
            CB_City.SelectedValue = 517;
        } 

您可以使用: CB_City.ItemsSource = c.Cities.OrderBy(c=>c.Text)CB_City.ItemsSource = c.Cities.OrderBy(c=>c.Text)

Another option is to use a CollectionViewSource with a SortDescription :

var myViewSource = new CollectionViewSource { Source = c.Cities.ToList() };
myViewSource.SortDescriptions.Add(
  new SortDescription("YOUR_PROPERTY", ListSortDirection.Ascending)
);
CB_City.ItemsSource = myViewSource.View;

Further to the post by @Ross, you can also get the CollectionViewSource this way:

var view = CollectionViewSource.GetDefaultView(CB_City.ItemsSource);
view.SortDescriptions.Add(new SortDescription("city1", 
    ListSortDirection.Ascending));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM