wpf treeview 选中节点加载数据并绑定
<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];
}
最新文章
- 使用 Spring Boot 快速构建 Spring 框架应用--转
- 设置Xshell中支持中文
- angularjs中$watch监听model(对象属性、对象)变化
- jBox使用记录
- Fail to start neutron-server
- 深入Java虚拟机读书笔记第一章Java体系结构介绍
- 表单javascript checkbox全选 反选 全不选
- MediaPlayer本地播放流程解析(一)
- 随学随用的python-note
- NSString+URLEncoding
- IIS7内建账号,应用程序池
- 在四川大学的第二个冠军游戏在线编程:Peter的X
- scapy流量嗅探简单使用
- 1688: [Usaco2005 Open]Disease Manangement 疾病管理
- 微信小程序(组件demo)以及预览方法:(小程序交流群:604788754)
- python 符合Python风格的对象
- mysql数据库表结构与表约束
- [转]Nginx基本功能极速入门
- [Cerc2013]Magical GCD
- 如何将MP3录音转文字