DevExpress的TreeList实现显示本地文件目录并自定义右键实现删除与重命名文件
場(chǎng)景
使用DevExpress的TreeList顯示本磁盤(pán)下文件目錄并在樹(shù)節(jié)點(diǎn)上右鍵實(shí)現(xiàn)刪除與添加文件。
效果
?
自定義右鍵效果
?
?
實(shí)現(xiàn)
首先在包含Treelist的窗體的load方法中對(duì)treelist進(jìn)行初始化
Common.DataTreeListHelper.RefreshTreeData(this.treeList1, 2);其中this.treeList1就是當(dāng)前窗體的treelist對(duì)象
然后第二個(gè)參數(shù)是默認(rèn)展開(kāi)級(jí)別。
public static void RefreshTreeData(DevExpress.XtraTreeList.TreeList treeList, int expandToLevel){string rootNodeId = Common.Global.AppConfig.TestDataDir;string rootNodeText =? ICSharpCode.Core.StringParser.Parse(ResourceService.GetString("Pad_DataTree_RootNodeText"));?? //"全部實(shí)驗(yàn)數(shù)據(jù)";string fieldName = "NodeText";string keyFieldName = "Id";string parentFieldName = "ParentId";List<DataTreeNode> data = new List<DataTreeNode>();data = DataTreeListHelper.ParseDir(Common.Global.AppConfig.TestDataDir, data);data.Add(new DataTreeNode() { Id = rootNodeId, ParentId = String.Empty, NodeText = rootNodeText, NodeType = DataTreeNodeTypes.Folder });DataTreeListHelper.SetTreeListDataSource(treeList, data, fieldName, keyFieldName, parentFieldName);treeList.ExpandToLevel(expandToLevel);}在上面方法中新建根節(jié)點(diǎn),根節(jié)點(diǎn)的Id就是要顯示的目錄,在配置文件中讀取。
根節(jié)點(diǎn)的顯示文本就是顯示“全部實(shí)驗(yàn)數(shù)據(jù)”,從配置文件中獲取。
然后調(diào)用工具類將目錄結(jié)構(gòu)轉(zhuǎn)換成帶父子級(jí)關(guān)系的節(jié)點(diǎn)的list,然后再將根節(jié)點(diǎn)添加到list。
然后調(diào)用設(shè)置treeList數(shù)據(jù)源的方法。
在上面方法中存取節(jié)點(diǎn)信息的DataTreeNode
public class DataTreeNode{private string id;private string parentId;private string nodeText;private string createDate;private string fullPath;private string taskFile;private string barcode;private DataTreeNodeTypes nodeType = DataTreeNodeTypes.Folder;public string Id{get { return id; }set { id = value; }}public string ParentId{get { return parentId; }set { parentId = value; }}public string NodeText{get { return nodeText; }set { nodeText = value; }}public string CreateDate{get { return createDate; }set { createDate = value; }}public string FullPath{get { return fullPath; }set { fullPath = value; }}public string TaskFile{get { return taskFile; }set { taskFile = value; }}public string Barcode{get { return barcode; }set { barcode = value; }}public DataTreeNodeTypes NodeType{get { return nodeType; }set { nodeType = value; }}}在上面方法中將目錄結(jié)構(gòu)轉(zhuǎn)換為節(jié)點(diǎn)list的方法
?public static List<DataTreeNode> ParseDir(string dataRootDir, List<DataTreeNode> data){if (data == null){data = new List<DataTreeNode>();}if (!System.IO.Directory.Exists(dataRootDir)){return data;}DataTreeNode node = null;System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(dataRootDir);System.IO.DirectoryInfo[] subDirs = dir.GetDirectories();foreach(System.IO.DirectoryInfo subDir in subDirs){node = new DataTreeNode();node.Id = subDir.FullName;node.ParentId = dir.FullName;node.NodeText = subDir.Name;node.CreateDate = String.Format("{0:yyyy-MM-dd HH:mm:ss}", subDir.CreationTime);node.FullPath = subDir.FullName;node.TaskFile = String.Empty;?????????? //任務(wù)文件名node.NodeType = DataTreeNodeTypes.Folder;data.Add(node);ParseDir(subDir.FullName, data);}System.IO.FileInfo[] subFiles = dir.GetFiles();return data;}通過(guò)遞歸將上面?zhèn)鬟f過(guò)來(lái)的目錄下的結(jié)構(gòu)構(gòu)造成節(jié)點(diǎn)的list并返回。
?
通過(guò)解析實(shí)驗(yàn)?zāi)夸浀姆椒ǚ祷豯ist后再調(diào)用刷新treelist節(jié)點(diǎn)的方法
SetTreeListDataSource
public static void SetTreeListDataSource(DevExpress.XtraTreeList.TreeList treeList, List<DataTreeNode> data, string fieldName, string keyFieldName, string parentFieldName){#region 設(shè)置節(jié)點(diǎn)圖標(biāo)System.Windows.Forms.ImageList imgList = new System.Windows.Forms.ImageList();imgList.Images.AddRange(imgs);treeList.SelectImageList = imgList;//目錄展開(kāi)treeList.AfterExpand -= treeList_AfterExpand;treeList.AfterExpand += treeList_AfterExpand;//目錄折疊treeList.AfterCollapse -= treeList_AfterCollapse;treeList.AfterCollapse += treeList_AfterCollapse;//數(shù)據(jù)節(jié)點(diǎn)單擊,開(kāi)啟整行選中treeList.MouseClick -= treeList_MouseClick;treeList.MouseClick += treeList_MouseClick;//數(shù)據(jù)節(jié)點(diǎn)雙擊選中treeList.MouseDoubleClick -= treeList_MouseDoubleClick;treeList.MouseDoubleClick += treeList_MouseDoubleClick;//焦點(diǎn)離開(kāi)事件treeList.LostFocus -= treeList_LostFocus;treeList.LostFocus += treeList_LostFocus;#endregion#region 設(shè)置列頭、節(jié)點(diǎn)指示器面板、表格線樣式treeList.OptionsView.ShowColumns = false;???????????? //隱藏列標(biāo)頭treeList.OptionsView.ShowIndicator = false;?????????? //隱藏節(jié)點(diǎn)指示器面板treeList.OptionsView.ShowHorzLines = false;?????????? //隱藏水平表格線treeList.OptionsView.ShowVertLines = false;?????????? //隱藏垂直表格線treeList.OptionsView.ShowIndentAsRowStyle = false;#endregion#region 初始禁用單元格選中,禁用整行選中treeList.OptionsView.ShowFocusedFrame = true;?????????????????????????????? //設(shè)置顯示焦點(diǎn)框treeList.OptionsSelection.EnableAppearanceFocusedCell = false;????????????? //禁用單元格選中treeList.OptionsSelection.EnableAppearanceFocusedRow = false;?????????????? //禁用正行選中//treeList.Appearance.FocusedRow.BackColor = System.Drawing.Color.Red;????? //設(shè)置焦點(diǎn)行背景色#endregion#region 設(shè)置TreeList的展開(kāi)折疊按鈕樣式和樹(shù)線樣式treeList.OptionsView.ShowButtons = true;????????????????? //顯示展開(kāi)折疊按鈕treeList.LookAndFeel.UseDefaultLookAndFeel = false;?????? //禁用默認(rèn)外觀與感覺(jué)treeList.LookAndFeel.UseWindowsXPTheme = true;??????????? //使用WindowsXP主題treeList.TreeLineStyle = DevExpress.XtraTreeList.LineStyle.Percent50;???? //設(shè)置樹(shù)線的樣式#endregion#region 添加單列DevExpress.XtraTreeList.Columns.TreeListColumn colNode = new DevExpress.XtraTreeList.Columns.TreeListColumn();colNode.Name = String.Format("col{0}", fieldName);colNode.Caption = fieldName;colNode.FieldName = fieldName;colNode.VisibleIndex = 0;colNode.Visible = true;colNode.OptionsColumn.AllowEdit = false;??????????????????????? //是否允許編輯colNode.OptionsColumn.AllowMove = false;??????????????????????? //是否允許移動(dòng)colNode.OptionsColumn.AllowMoveToCustomizationForm = false;???? //是否允許移動(dòng)至自定義窗體colNode.OptionsColumn.AllowSort = false;??????????????????????? //是否允許排序colNode.OptionsColumn.FixedWidth = false;?????????????????????? //是否固定列寬colNode.OptionsColumn.ReadOnly = true;????????????????????????? //是否只讀colNode.OptionsColumn.ShowInCustomizationForm = true;?????????? //移除列后是否允許在自定義窗體中顯示treeList.Columns.Clear();treeList.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] { colNode });#endregion#region 綁定數(shù)據(jù)源treeList.DataSource = null;treeList.KeyFieldName = keyFieldName;treeList.ParentFieldName = parentFieldName;treeList.DataSource = data;treeList.RefreshDataSource();#endregion#region 初始化圖標(biāo)SetNodeImageIndex(treeList.Nodes.FirstOrDefault());#endregion}如果不考慮根據(jù)文件還是文件夾設(shè)置節(jié)點(diǎn)圖標(biāo)和綁定其他雙擊事件等。
直接關(guān)注鼠標(biāo)單擊事件的綁定和下面初始化樣式的設(shè)置。
在單擊鼠標(biāo)節(jié)點(diǎn)綁定的方法中
private static void treeList_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e){DevExpress.XtraTreeList.TreeList treeList = sender as DevExpress.XtraTreeList.TreeList;if (treeList != null && treeList.Selection.Count == 1){object idValue = null;string strIdValue = String.Empty;DataTreeNode nodeData = null;List<DataTreeNode> datasource = treeList.DataSource as List<DataTreeNode>;if (datasource != null){idValue = treeList.Selection[0].GetValue("Id");strIdValue = idValue.ToString();nodeData = datasource.Where<DataTreeNode>(p => p.Id == strIdValue).FirstOrDefault<DataTreeNode>();if (nodeData != null){if (nodeData.NodeType == DataTreeNodeTypes.File){treeList.OptionsSelection.EnableAppearanceFocusedRow = true;??????????????????????????????? //啟用整行選中if (e.Button == System.Windows.Forms.MouseButtons.Right){System.Windows.Forms.ContextMenu ctxMenu = new System.Windows.Forms.ContextMenu();#region 右鍵彈出上下文菜單 - 刪除數(shù)據(jù)文件System.Windows.Forms.MenuItem mnuDelete = new System.Windows.Forms.MenuItem();mnuDelete.Text = "刪除";mnuDelete.Click += delegate(object s, EventArgs ea) {DialogResult dialogResult = DevExpress.XtraEditors.XtraMessageBox.Show(String.Format("確定要?jiǎng)h除此實(shí)驗(yàn)數(shù)據(jù)嗎[{0}]?\r\n刪除后無(wú)法恢復(fù)!", nodeData.Id), "標(biāo)題", System.Windows.Forms.MessageBoxButtons.YesNo, MessageBoxIcon.Question);if (dialogResult == DialogResult.Yes){try{string fileName = String.Empty;#region 刪除數(shù)據(jù)文件fileName = String.Format("{0}{1}", nodeData.Id, Global.MAIN_EXT);if (System.IO.File.Exists(fileName)){System.IO.File.Delete(fileName);}#endregion#region 刪除對(duì)應(yīng)的樹(shù)節(jié)點(diǎn)DevExpress.XtraTreeList.Nodes.TreeListNode selectedNode = treeList.FindNodeByKeyID(nodeData.Id);if (selectedNode != null){selectedNode.ParentNode.Nodes.Remove(selectedNode);}#endregiontreeList.OptionsSelection.EnableAppearanceFocusedRow = false;??????????????????????????????? //禁用整行選中}catch(Exception ex){ICSharpCode.Core.LoggingService<DataTreeListHelper>.Error("刪除實(shí)驗(yàn)數(shù)據(jù)異常:" + ex.Message, ex);DevExpress.XtraEditors.XtraMessageBox.Show("刪除實(shí)驗(yàn)數(shù)據(jù)異常:" + ex.Message, "標(biāo)題", MessageBoxButtons.OK,MessageBoxIcon.Error);}}};ctxMenu.MenuItems.Add(mnuDelete);#endregion#region 右鍵彈出上下文菜單 - 重命名數(shù)據(jù)文件System.Windows.Forms.MenuItem mnuReName = new System.Windows.Forms.MenuItem();mnuReName.Text = "重命名";mnuReName.Click += delegate(object s, EventArgs ea){//獲取當(dāng)前文件名string oldName = Path.GetFileNameWithoutExtension(strIdValue);Dialog.FrmReName frmReName = new FrmReName(oldName);frmReName.StartPosition = FormStartPosition.CenterScreen;DialogResult result = frmReName.ShowDialog();if (result == DialogResult.OK){//刷入框新設(shè)置的文件名string newName = frmReName.FileName;//獲取原來(lái)路徑string filePath = Path.GetDirectoryName(strIdValue);//使用原來(lái)路徑加 + 新文件名 結(jié)合成新文件路徑string newFilePath = Path.Combine(filePath, newName);DialogResult dialogResult = DevExpress.XtraEditors.XtraMessageBox.Show(String.Format("確定要將實(shí)驗(yàn)數(shù)據(jù)[{0}]重命名為[{1}]嗎?", nodeData.Id, newName), "標(biāo)題", System.Windows.Forms.MessageBoxButtons.YesNo, MessageBoxIcon.Question);if (dialogResult == DialogResult.Yes){try{string fileName = String.Empty;string newFileName = String.Empty;#region 重命名主通道數(shù)據(jù)文件fileName = String.Format("{0}{1}", nodeData.Id, Global.MAIN_EXT);newFileName = String.Format("{0}{1}", newFilePath, Global.MAIN_EXT);if (System.IO.File.Exists(fileName)){FileInfo fi = new FileInfo(fileName);fi.MoveTo(newFileName);}#endregion//刷新樹(shù)Common.DataTreeListHelper.TriggerRefreshDataEvent();XtraMessageBox.Show("重命名成功");treeList.OptionsSelection.EnableAppearanceFocusedRow = false;??????????????????????????????? //禁用整行選中}catch (Exception ex){ICSharpCode.Core.LoggingService<DataTreeListHelper>.Error("刪除實(shí)驗(yàn)數(shù)據(jù)異常:" + ex.Message, ex);DevExpress.XtraEditors.XtraMessageBox.Show("刪除實(shí)驗(yàn)數(shù)據(jù)異常:" + ex.Message, "標(biāo)題", MessageBoxButtons.OK,MessageBoxIcon.Error);}}}};ctxMenu.MenuItems.Add(mnuReName);#endregion#endregionctxMenu.Show(treeList, new System.Drawing.Point(e.X, e.Y));}return;}}}treeList.OptionsSelection.EnableAppearanceFocusedRow = false;??????????????????????????????? //禁用整行選中}}其中在進(jìn)行重命名時(shí)需要彈出一個(gè)窗體
具體實(shí)現(xiàn)參照:
Winform巧用窗體設(shè)計(jì)完成彈窗數(shù)值綁定-以重命名彈窗為例:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/103155532
總結(jié)
以上是生活随笔為你收集整理的DevExpress的TreeList实现显示本地文件目录并自定义右键实现删除与重命名文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Winform巧用窗体设计完成弹窗数值绑
- 下一篇: C#中在多个地方调用同一个触发器从而触发