-->

我怎么排序绑定了一个项目的子类的属性项的WPF的TreeView?(How do I sort a

2019-09-16 13:30发布

我有两个班,

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结合树形视图项目书项目的收集和显示产品子类的说明和代码,树形视图填充和正确显示,但现在我要到TreeView在任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>

我有正确的代码工作,为其他树视图,所以我只能猜测它是绑定到一个子类的问题。

Answer 1:

虽然这里的答案提供了部分答案我的问题,他们没有给我所需要的答案。

此问题的最明智的解决办法是写我自己的对象比较器此对象类型和排序的基础列表,然后重新绑定新的列表到TreeView。 这使得在任何嵌套的水平,这我不能做任何其他的工作方式比较sublasses :)



Answer 2:

你需要让每个子列表中的默认视图,并应用CollectionViewSource排序它。 您发布的代码只影响顶级项目。



Answer 3:

绑定您TreeView.ItemsSource的默认视图。 SortDescriptions不会改变你的DataList,只有它的视图。

tvList.ItemsSource = bookItemsSort;

见衣Stollnitz博客: 我如何排序的层级?



文章来源: How do I sort a WPF treeview that has items bound to the properties of an Item subclass?