我有两个班级,
public class BookItem
{
public string BookID { get; set; }
public string ItemID { get; set; }
public Item Item { get; set; }
public ItemType Type { get; set; }
public string ParentID { get; set; }
public string BoxID { get; set; }
public string StyleID { get; set; }
public string NotesID { get; set; }
public string Code_XAML { get; set; }
public string Description_XAML { get; set; }
public CompositeCollection SubItems { get; set; }
}
public class Item : ClaunchBaseClass
{
public string ItemID { get; set; }
public int Type { get; set; }
public string Code { get; set; }
public string Description { get; set; }
private BookList _books = new BookList();
public BookList Books { get {return _books;} set { _books = value; }}
}
我创建了以下XAML:
<pre>
<TreeView Name="tvList" Grid.Row="2" MouseDoubleClick="tvList_MouseDoubleClick">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="x:Type j:BookItem" ItemsSource="{Binding SubMenu}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Item.Code}" Grid.Column="0" />
<TextBlock Text="{Binding Item.Description}" Grid.Column="1"/>
</Grid>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<code>
此XAML将树视图项绑定到书项集合并显示Item子类的描述和代码,树视图正确填充和显示但现在我想在Item.Code或Item.Description上对树视图进行排序并尝试过以下没有结果:
<pre>
var bookItemsSort = CollectionViewSource.GetDefaultView(_bookItemList) as ListCollectionView;
tvList.ItemsSource = _bookItemList; //bind the book items to the treeview
bookItemsSort.SortDescriptions.Clear();
bookItemsSort.SortDescriptions.Add(new SortDescription(sort, Ascending));
<code>
我已经将此代码正确地用于其他树视图,因此我只能猜测它是绑定到子类的问题。
答案 0 :(得分:2)
虽然这里的答案提供了我问题的部分答案,但他们都没有给出我需要的答案。
此问题最明智的解决方案是为此对象类型编写自己的对象比较器,并对基础列表进行排序,然后将新列表重新绑定到树视图。这允许比较任何嵌套级别的子类,我无法以任何其他方式工作:)
答案 1 :(得分:0)
将TreeView.ItemsSource
绑定到DefaultView。 SortDescriptions不会更改您的DataList,只会更改它的视图。
tvList.ItemsSource = bookItemsSort;
见Bea Stollnitz博客:How can I sort a hierarchy?
答案 2 :(得分:0)
您需要获取每个子列表的默认视图,并对其应用CollectionViewSource排序。您发布的代码仅影响顶级项目。