开发者

Grouping and sorting for TreeView in xaml

I am having problems getting my head around grouping and sorting in xaml and hope someone can get me straightened out!

I have created an xml file from a tree of files and folders (just like windows explorer) that can be several levels deep. I have bound a TreeView control to an xml datasource and it works great! It sorts everything alphabetically but ... I would like it to sort all folders first then all files, rather than folders listed with files, as it does now.

the xml :

if you load this to a treeviw it will display the two files before the folder because they are first in alpha-order.

here is my code:

  <!-- This will contain the XML-data. -->
  <XmlDataProvider x:Key="xmlDP" XPath="*">
     <x:XData>
        <Select_Project />
     </x:XData>
  </XmlDataProvider>

  <!-- This HierarchicalDataTemplate will visualize all XML-nodes -->
  <HierarchicalDataTemplate DataType="project" ItemsSource ="{Binding}">
     <TextBlock Text="{Bind开发者_如何学Cing XPath=@name}" />
  </HierarchicalDataTemplate>

  <HierarchicalDataTemplate DataType="folder" ItemsSource ="{Binding}">
     <TextBlock Text="{Binding XPath=@name}" />
  </HierarchicalDataTemplate>

  <HierarchicalDataTemplate DataType="file" ItemsSource ="{Binding}">
     <TextBlock Text="{Binding XPath=@name}" />
  </HierarchicalDataTemplate>

  <CollectionViewSource x:Key="projectView" Source="{StaticResource xmlDP}">
     <CollectionViewSource.SortDescriptions>
        <!-- ADD SORT DESCRIPTION HERE -->
     </CollectionViewSource.SortDescriptions>
  </CollectionViewSource>

  <TreeView Margin="11,79.992,18,19.089" 
            Name="tvProject" 
            BorderThickness="1" FontSize="12" FontFamily="Verdana">

     <TreeViewItem ItemsSource="{Binding Source={StaticResource xmlDP}, XPath=*}"  
                   Header="Project"/>
  </TreeView>


Try adding another attribute to your XML file, I'll call it FileType, but you can call it whatever your like. For this element specify it to be equal to "Folder" or "File". Now you must do to levels of sorting. First sort Decending on FileType (Folders first, Files second), then sort on the Name attribute. In other words, you XML would like like this:

<project name="ProjectName" >
    <file name="alphacat.html" FileType="File" />
    <file name="aztec.html" FileType="File" />
    <folder name="FolderA" FileType="Folder" >
        <file name="application.asp" FileType="File" />
        <file name="work.asp" FileType="File" /> 
    </folder> 
</project>

Does that help?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜