效果图
逻辑代码
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { foreach(var drive in Directory.GetLogicalDrives()) { var item = new TreeViewItem() { Header = drive, Tag = drive }; item.Items.Add(null); item.Expanded += Folder_Expanded; this.FolderView.Items.Add(item); } } private void Folder_Expanded(object sender, RoutedEventArgs e) { var item = (TreeViewItem)sender; if(item.Items.Count != 1 || item.Items[0] != null) { return; } item.Items.Clear(); var fullPath = (string)item.Tag; var files = new List<string>(); try { var fs = Directory.GetFiles(fullPath); if(fs.Length>0) { files.AddRange(fs); } fs = Directory.GetDirectories(fullPath); if (fs.Length > 0) { files.AddRange(fs); } } catch { } files.ForEach(directoryPath => { var subItem = new TreeViewItem() { Header = GetFileFolderName(directoryPath), Tag = directoryPath }; subItem.Items.Add(null); subItem.Expanded += Folder_Expanded; item.Items.Add(subItem); }); } public static string GetFileFolderName(string path) { if(string.IsNullOrEmpty(path)) { return string.Empty; } var normalizedPath = path.Replace('/', '\'); var lastIndex = normalizedPath.LastIndexOf('\'); if(lastIndex <0) { return path; } return path.Substring(lastIndex + 1); } }
样式代码
<Window x:Class="Wpf02TreeViews.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Wpf02TreeViews" mc:Ignorable="d" Loaded="Window_Loaded" Title="MainWindow" Height="350" Width="525"> <StackPanel> <TreeView x:Name="FolderView" > <TreeView.Resources> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="HeaderTemplate"> <Setter.Value> <DataTemplate> <StackPanel Orientation="Horizontal"> <Image Width="20" Margin="3" Source="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}, Path=Tag, Converter={x:Static local:HeaderToImageConverter.Instance}}"></Image> <TextBlock VerticalAlignment="Center" Text="{Binding}"></TextBlock> </StackPanel> </DataTemplate> </Setter.Value> </Setter> </Style> </TreeView.Resources> </TreeView> </StackPanel> </Window>