<Window x:Class="TsyCreateProjectContent.Window1"
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:TsyCreateProjectContent"
mc:Ignorable="d"
Loaded="Window_Loaded_V1"
Title="test" Height="525" Width="540" ResizeMode="NoResize">
<Grid Height="525" VerticalAlignment="Top" ShowGridLines="False">
<TreeView Grid.Row="0" Grid.Column="0" x:Name="FolderView" Canvas.Top="1" Canvas.Bottom="1" VerticalAlignment="Stretch"
MouseLeftButtonUp="FolderView_MouseLeftButtonUp" Margin="5,5,15,5" Width="500">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:TreeViewData}" ItemsSource="{Binding Path=Children}">
<StackPanel Orientation="Horizontal">
<Image Margin="3" Width="20" Source="{Binding ImgName}"/>
<TextBlock VerticalAlignment="Center" Text="{Binding HeaderName }" Tag="{Binding TagValue}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
<Setter Property="IsExpanded" Value="{Binding IsExpanded}" />
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
</Grid>
</Window>
private void Window_Loaded_V1(object sender, RoutedEventArgs e)
{
List<TreeViewData> rootList = new List<TreeViewData>();
TreeViewData rootItem = new TreeViewData();
rootItem.HeaderName = "我的电脑";
rootItem.TagValue = "我的电脑";
rootItem.ImgName = "Images/windows.png";
rootItem.IsExpanded = true;
rootItem.IsSelected = true;
rootItem.Children = new List<TreeViewData>();
rootList.Add(rootItem);
// 将其添加到主树视图
//FolderView.Items.Add(rootItem);
DriveInfo[] drivers = DriveInfo.GetDrives();
// 获取电脑上的每个逻辑驱动器
foreach (var drive in Directory.GetLogicalDrives())
{
var childItem = new TreeViewData();
childItem.HeaderName = drive;
childItem.TagValue = drive;
childItem.ImgName = "Images/drive.png";
rootItem.IsExpanded = true;
rootItem.IsSelected = false;
childItem.Children = new List<TreeViewData>();
rootItem.Children.Add(childItem);
}
FolderView.ItemsSource = rootList;
}