2010-08-23 2 views
0

Я видел, как ICollectionView вводится с WPF для обработки ситуаций, когда вам нужна сортировка и фильтрация. Я даже видел несколько статей, которые сортируют элементы, но моя главная проблема заключается в том, почему мой подход терпит неудачу. Давайте посмотрим, мой код:Проблема сортировки ICollectionView в ListView

<ListView ItemsSource="{Binding}" x:Name="lvItems" GridViewColumnHeader.Click="ListView_Click"> 
      <ListView.View> 
       <GridView AllowsColumnReorder="True"> 
        <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}" /> 
        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" /> 
        <GridViewColumn Header="Developer"> 
         <GridViewColumn.CellTemplate> 
          <DataTemplate> 
           <TextBlock Text="{Binding Path=Developer}" /> 
          </DataTemplate> 
         </GridViewColumn.CellTemplate> 
        </GridViewColumn> 
        <GridViewColumn Header="Salary"> 
         <GridViewColumn.CellTemplate> 
          <DataTemplate> 
           <TextBlock Text="{Binding Path=Salary}" /> 
          </DataTemplate> 
         </GridViewColumn.CellTemplate> 
        </GridViewColumn> 

       </GridView> 
      </ListView.View> 
     </ListView> 

В коде, когда товар щелкнул я делаю так:

ICollectionView Source { get; set; } 


     private void ListView_Click(object sender, RoutedEventArgs e) 
     { 
      GridViewColumnHeader currentHeader = e.OriginalSource as GridViewColumnHeader; 
      if(currentHeader != null && currentHeader.Role != GridViewColumnHeaderRole.Padding) 
      { 
       //using (this.Source.DeferRefresh()) 
       //{ 
        SortDescription currentPropertySort = this.Source.SortDescriptions.FirstOrDefault<SortDescription>(item => item.PropertyName.Equals(currentHeader.Column.Header.ToString())); 
        if (currentPropertySort != null) 
        { 
         if (currentPropertySort.Direction == ListSortDirection.Ascending) 
          currentPropertySort.Direction = ListSortDirection.Descending; 
         else 
          currentPropertySort.Direction = ListSortDirection.Ascending; 

        } 
        else 
         this.Source.SortDescriptions.Add(new SortDescription(currentHeader.Column.Header.ToString(), ListSortDirection.Ascending)); 


       //} 
        this.Source.Refresh(); 
        this.lvItems.DataContext = this.Source; 
        this.lvItems.UpdateLayout(); 
      } 


     } 

Поэтому, когда заголовок для ListBox щелкают, деталь нужно сортировать. Я держу коллекцию, используя свойство Source, а затем использую его, вызывая lvItems.DataContext = this.Source. Но код, похоже, не работает.

Любая помощь? Я также добавил код http://cid-bafa39a62a57009c.office.live.com/self.aspx/.Public/CollectionviewSourceSample.zip

+0

Для всех зрителей этого сообщения я уже реализовал это. Если вы хотите посмотреть, посмотрите: http://www.abhisheksur.com/2010/08/woring-with-icollectionviewsource-in.html Thanks – abhishek

ответ

3

Ниже приведена обновленная версия метода ListView_Click, который несколько работает. Я не уверен точно, какое поведение сортировки вы искали, но приведенная ниже версия «складывает» набор описаний сортировки, в результате чего последний щелкнул столбец как «основное описание сортировки». Надеюсь, это имеет смысл, и я надеюсь, что код ниже помогает. =)

private void ListView_Click(object sender, RoutedEventArgs e) 
{ 
    GridViewColumnHeader currentHeader = e.OriginalSource as GridViewColumnHeader; 
    if(currentHeader != null && currentHeader.Role != GridViewColumnHeaderRole.Padding) 
    { 
     if (this.Source.SortDescriptions 
      .Count((item) => item.PropertyName.Equals(currentHeader.Column.Header.ToString())) > 0)     
     { 
      SortDescription currentPropertySort = this.Source 
       .SortDescriptions 
       .First<SortDescription>(item => item.PropertyName.Equals(currentHeader.Column.Header.ToString())); 

      //Toggle sort direction. 
      ListSortDirection direction = 
       (currentPropertySort.Direction == ListSortDirection.Ascending)? 
       ListSortDirection.Descending : ListSortDirection.Ascending; 

      //Remove existing sort 
      this.Source.SortDescriptions.Remove(currentPropertySort); 
      this.Source.SortDescriptions.Insert(0, new SortDescription(currentHeader.Column.Header.ToString(), direction)); 
     } 
     else 
     { 
      this.Source.SortDescriptions.Insert(0, new SortDescription(currentHeader.Column.Header.ToString(), ListSortDirection.Ascending)); 
     } 

     this.Source.Refresh(); 
    } 
} 

EDIT:

Кстати, одна из проблем в коде выше ваш призыв к "FirstOrDefault" для запроса существующего SortDescription. См., SortDescription - это структура, которая не является нулевой, поэтому вызов FirstOrDefault никогда не будет равен и всегда будет возвращать экземпляр. Поэтому «else-statement» в вашем коде выше никогда не будет вызван.

+0

Wow thats great. Я просто забыл тип SortDescription и, следовательно, больше кредитов для вас, указав на меня с этим. Большое вам спасибо за ваш код. – abhishek

+0

В моем случае ListView только был отсортирован в первый раз, а Refresh() не работает вообще! Так в чем проблема? – ARZ

Смежные вопросы