C# 将ItemSource与ListViewItem一起用于排序

C# 将ItemSource与ListViewItem一起用于排序,c#,wpf,xaml,C#,Wpf,Xaml,我对WPF中的listView排序有问题。这可以使用绑定,但我想继续使用ListViewItems进行操作。我的问题是ItemSource默认为null。若我像bellow一样设置itemsource,它不为null,但我的排序函数不起作用 ObservableCollection<ListViewItem> allFormats = new ObservableCollection<ListViewItem>(); foreach (Item drd in format

我对WPF中的listView排序有问题。这可以使用绑定,但我想继续使用ListViewItems进行操作。我的问题是ItemSource默认为null。若我像bellow一样设置itemsource,它不为null,但我的排序函数不起作用

ObservableCollection<ListViewItem> allFormats = new ObservableCollection<ListViewItem>();
foreach (Item drd in formats) {
  ListViewItem lvi = new ListViewItem();
  // Section with ListViewItem manipulation. Set drd values, set tag etc...
  allFormats.Add(lvi);
}
lvFormats.ItemsSource = (ICollectionView)CollectionViewSource.GetDefaultView(allFormats);

在绑定这项工作中,因为我直接在集合视图中拥有类。这里我有
CurrentItem={System.Windows.Controls.ListViewItem:{cFormats=aaaa,cFormatID=3,cFormatIDVersion=6}}
。在xaml中,我不使用绑定。

那些“ListViewItem操作”应该在xaml中的ItemContainerStyle中完成。您不应该手动创建ListViewItems。@Clemens。为什么手动创建ListViewItems不好?因为通常不建议在代码隐藏中创建UI元素。WPF有模板的概念,即控制模板和数据模板。将项传递给类似ListView的ItemsControl的典型方法是将其ItemsSource属性绑定到数据项集合。然后通过设置ItemTemplate属性或声明由其DataType属性自动选择的DataTemplates来定义这些项的显示方式。看见
private void Sort(string sortBy, ListSortDirection direction)
        {
            CollectionView dataView = (CollectionView)CollectionViewSource.GetDefaultView(this.ItemsSource);

            if (dataView != null)
            {
                dataView.SortDescriptions.Clear();
                SortDescription sd = new SortDescription(sortBy, direction);
                dataView.SortDescriptions.Add(sd);
                dataView.Refresh();
            }
        }