开发者

How can I keep an observable collection sorted in a listbox?

开发者 https://www.devze.com 2023-01-06 03:24 出处:网络
I have the following to get data from an Entity Framework 4: IQueryable<Exam> examsQuery = entities.CreateQuery<Exam>(\"[Exams]\").Include(\"Course\");

I have the following to get data from an Entity Framework 4:

IQueryable<Exam> examsQuery = 
   entities.CreateQuery<Exam>("[Exams]").Include("Course");
exams = 
   new EntityObservableCollection<Exam>(entities, "Exams", examsQuery);

In my viewmodel I have the following code:

public IEnumerable<Exam> Exams { get { return exams; } }

And in my XAML the following:

<ListView ItemsSource="{Binding Exams}" SelectedItem="{Binding SelectedExam}" 
   SelectionChanged="ListViewSelectionChanged">
      <ListView.View>
          <GridView>
              <GridViewColumn DisplayMemberBinding="{Binding 开发者_开发知识库Code}" Header="ExamCode" Width="250"/>
              <GridViewColumn DisplayMemberBinding="{Binding Desc}" Header="Desc" Width="150"/>
              <GridViewColumn DisplayMemberBinding="{Binding Course.Code}" Header="Course" Width="150"/>
           </GridView>
       </ListView.View>
</ListView>

The problem for me is that firstly I would like to have:

1) ListView sorted on ExamCode column 2) I would like to have it remain sorted if for example the ExamCode is changed externally.

Is there an easy way to always keep a listview sorted? I have looked around and can't find a solution at all.

Thanks


Use ICollectionView:

public ICollectionView Exams 
{ 
    get 
    { 
         if (examsView == null)
         {
             examsView = CollectionViewSource.GetDefaultView(exams); 
             examsView.SortDescriptions.Add(new SortDescription("Code",  ListSortDirection.Descending)); // your sort here
         }

         return examsView;
    } 
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消