<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">
FolderView_MouseLeftButtonUp 鼠标事件
private void FolderView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
TreeViewData selectItem = FolderView.SelectedItem as TreeViewData;
if (selectItem != null)
{
txtSelectPath.Text = selectItem.TagValue.ToString();
selectItem.IsSelected = true;
selectItem.IsExpanded = true;
if (txtSelectPath.Text != "我的电脑") {
if (selectItem.Children.Count <= 0)
{
selectItem.Children = LoadItemFiles(selectItem);
if (selectItem.Children.Count > 0)
{
FolderView.Items.Refresh();
}
}
}
}
}
private List<TreeViewData> LoadItemFiles(TreeViewData item)
{
List<TreeViewData> rootList = new List<TreeViewData>();
// 获取完整路径
var fullPath = (String)item.TagValue;
#region Get Folders
// 为目录创建一个空白列表
var directories = new List<String>();
// 尝试从文件夹中获取目录 // try异常处理,忽略出现的任何问题
try
{
var dirs = Directory.GetDirectories(fullPath);
{
if (dirs.Length > 0)
directories.AddRange(dirs);
}
}
catch
{
}
#endregion
// 为目录做迭代,添加目录
directories.ForEach(directoryPath =>
{
// 创建目录项
var subItem = new TreeViewItem()
{
// 将标题设置为文件夹名称
Header = GetFileFolderName(directoryPath),
// 标记为完整路径
Tag = directoryPath
};
TreeViewData itemData = new TreeViewData();
itemData.HeaderName = GetFileFolderName(directoryPath);
itemData.TagValue = directoryPath;
itemData.ImgName = "Images/file.png";
itemData.Children = new List<TreeViewData>();
rootList.Add(itemData);
});
return rootList;
}
public static string GetFileFolderName(string path)
{
// 如果没有路径,则返回空
if (string.IsNullOrEmpty(path))
return string.Empty;
var files = path.Split('\\');
return files[files.Count() - 1];
}