在标题上应用排序后如何刷新WPF树视图内容?

时间:2018-10-29 09:17:29

标签: c# wpf treeview treeviewitem

我有一个显示文件夹结构的树状视图(文件夹和文件在其下)。

我想添加一个按钮,以允许按字母顺序对内容(文件)进行排序。

这是我的实现方式:

XAML

<TreeView Name="WorkspaceTree" Grid.Row="1" FontSize="13" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="200" IsTextSearchEnabled="True" SelectedItemChanged="ProjectWorkspace_SelectedItemChanged" MouseRightButtonDown="ProjectWorkspace_MouseRightButtonDown" MouseDoubleClick="ProjectWorkspace_MouseDoubleClick">
   <TreeView.Resources>
      <ContextMenu x:Key ="FolderContext"  StaysOpen="true">
           <MenuItem x:Name="ProjectWorkspace_OpenAll" Header="Open All" Click="ProjectWorkspace_OpenAll_Click"/>
      </ContextMenu>
      <ContextMenu x:Key="ReaderContext"  StaysOpen="true">
           <MenuItem x:Name="ProjectWorkspace_Open" Header="Open" Click="ProjectWorkspace_Open_Click"/>
           <MenuItem x:Name="ProjectWorkspace_Build" Header="Build" Click="ProjectWorkspace_Build_Click"/>
      </ContextMenu>
   </TreeView.Resources>
   No workspace was loaded...
</TreeView>

树被后面的代码填充。这是快照。

      ...

      WorkspaceTree.Items.Clear();
      var rootDirectoryInfo = new DirectoryInfo(dlg.FileName);
      TreeViewItem root_item = CreateDirectoryNode(rootDirectoryInfo);
      if (root_item != null)
      {
          WorkspaceTree.Items.Add(root_item);
          ...
}

private static TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)
{
     var directoryNode = new TreeViewItem { Header = directoryInfo.Name, Tag = "Folder" };
     foreach (var directory in directoryInfo.GetDirectories())
     {
         TreeViewItem dir_recursive_item = CreateDirectoryNode(directory);
         if (dir_recursive_item != null)
             directoryNode.Items.Add(dir_recursive_item);
         }

         foreach (var file in directoryInfo.GetFiles("*.txt"))
         directoryNode.Items.Add(new TreeViewItem { Header = file.Name, Tag = file.FullName });
         if (directoryNode.Items.Count == 0)
            return null;
         return directoryNode;
     }
}

现在,在显示树之后,通过UI交互,应该对它的内容进行排序。 我放置了一个按钮,其点击事件为:

private void Sort_Click(object sender, RoutedEventArgs e)
{
    WorkspaceTree.Items.SortDescriptions.Clear();
    WorkspaceTree.Items.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending));
}

事件正在运行时-树本身没有任何反应。

我尝试在Header.Name中对SortDescription进行排序,但行为没有变化。

我想念什么?

0 个答案:

没有答案